﻿using Abp.Application.Services.Dto;
using Abp.Authorization.Users;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.EntityFrameworkCore.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.Runtime.Session;
using Abp.UI;
using Camc.Quality.Authorization.Users;
using Camc.Quality.Bom.BomInterface;
using Camc.Quality.Bom.Dto;
using Camc.Quality.BomChange;
using Camc.Quality.Bop;
using Camc.Quality.Bop.Dto;
using Camc.Quality.Business;
using Camc.Quality.Common;
using Camc.Quality.DataDictionary;
using Camc.Quality.IOperationHistory;
using Camc.Quality.Materials;
using Camc.Quality.Materials.Dto;
using Camc.Quality.OperationHistory;
using Camc.Quality.ProductionPlan;
using Camc.Quality.StoreManagement.SoreModel.Dto;
using Camc.Quality.SystemManagement;
using Camc.Quality.WorkFlow;
using EFCore.BulkExtensions;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Camc.Quality.Bom
{
    public class BomContentAppService : QualityAppServiceBase
    {
        private readonly IRepository<MaterialsContent, Guid> _materialsContentrepository;
        private readonly IRepository<MaterialsNode, Guid> _materialsNoderepository;
        private readonly IRepository<BomDesign, Guid> _bomDesignrepository;
        private readonly IRepository<BomDesignDetail, Guid> _bomDesignDetailrepository;
        private readonly IRepository<Sys_Code, Guid> _sysCodeRepository;
        List<BomDesign> bomEditLists = new List<BomDesign>();
        List<BomDesignDetail> bomdetaillists = new List<BomDesignDetail>();
        private readonly IRepository<User, long> _userRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IAbpSession _abpSession;
        private readonly IOperationHistoryAppService _iOperationHistoryAppService;
        private readonly IBomExportToExcel _bomExportToExcel;
        private readonly WorkFlowAppService _workFlowAppService;
        private readonly IRepository<ModifyManage, Guid> _modifyManageRepository;
        private readonly IRepository<BomChangeContent, Guid> _bomChangeContentRepository;
        private readonly IRepository<BusinessApplication, Guid> _businessApplicationRepository;
        private readonly IRepository<WorkFlowNode, Guid> _workFlowNodeRepository;
        private readonly IRepository<WorkAuditor, Guid> _workAuditorRepository;
        private readonly IRepository<UserRole, long> _userRoleRepository;
        private readonly MaterialsAppService _materialsAppService;
        Guid BomGuid = Guid.Empty;
        private readonly IBomImportToTable _bomImportToTable = new BomImportToTable();
        List<BomDesignDetail> bomDesignDetails = new List<BomDesignDetail>();
        List<BomEditChildData> bomDetaillists = new List<BomEditChildData>();
        public readonly CodeFormatDescAppService _codeFormatDescAppServiceRepository;
        private readonly IRepository<MakeTask, Guid> _makeTaskRepository;
     
        //   private readonly IRepository<BomParentLevel, Guid> _bomParentLevelrepository;
        public BomContentAppService(IRepository<MakeTask, Guid> makeTaskRepository, IRepository<MaterialsContent, Guid> materialsContentrepository, IRepository<UserRole, long> userRoleRepository, IRepository<MaterialsNode, Guid> materialsNoderepository, IRepository<BomDesign, Guid> bomDesignrepository, IRepository<BomDesignDetail, Guid> bomDesignDetailrepository, IRepository<User, long> userRepository, IOperationHistoryAppService iOperationHistoryAppService, IAbpSession abpSession, IBomExportToExcel bomExportToExcel, IRepository<Sys_Code, Guid> sysCodeRepository, WorkFlowAppService workFlowAppService, IRepository<ModifyManage, Guid> modifyManageRepository, IRepository<BomChangeContent, Guid> bomChangeContentRepository, IRepository<BusinessApplication, Guid> businessApplicationRepository, IRepository<WorkFlowNode, Guid> workFlowNodeRepository, IRepository<WorkAuditor, Guid> workAuditorRepository, MaterialsAppService materialsAppService, IUnitOfWorkManager unitOfWorkManager, CodeFormatDescAppService codeFormatDescAppServiceRepository)
        {
            _bomDesignDetailrepository = bomDesignDetailrepository;
            _materialsNoderepository = materialsNoderepository;
            _bomDesignrepository = bomDesignrepository;
            _materialsContentrepository = materialsContentrepository;
            _userRepository = userRepository;
            _iOperationHistoryAppService = iOperationHistoryAppService;
            _abpSession = abpSession;
            _bomExportToExcel = bomExportToExcel;
            _sysCodeRepository = sysCodeRepository;
            _workFlowAppService = workFlowAppService;
            _modifyManageRepository = modifyManageRepository;
            _bomChangeContentRepository = bomChangeContentRepository;
            _businessApplicationRepository = businessApplicationRepository;
            _workFlowNodeRepository = workFlowNodeRepository;
            _workAuditorRepository = workAuditorRepository;
            _userRoleRepository = userRoleRepository;
            _materialsAppService = materialsAppService;
            _unitOfWorkManager = unitOfWorkManager;
            _codeFormatDescAppServiceRepository = codeFormatDescAppServiceRepository;
            _makeTaskRepository = makeTaskRepository;
        }
        private bool CopyDir(string srcPath, string aimPath)
        {
            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加
                if (aimPath[aimPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
                {
                    aimPath += System.IO.Path.DirectorySeparatorChar;
                }
                // 判断目标目录是否存在如果不存在则新建
                if (!System.IO.Directory.Exists(aimPath))
                {
                    System.IO.Directory.CreateDirectory(aimPath);
                }
                // 得到源目录的文件列表，该里面是包含文件以及目录路径的一个数组
                // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
                // string[] fileList = Directory.GetFiles（srcPath）；
                string[] fileList = System.IO.Directory.GetFileSystemEntries(srcPath);
                // 遍历所有的文件和目录
                foreach (string file in fileList)
                {
                    // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                    if (System.IO.Directory.Exists(file))
                    {
                        CopyDir(file, aimPath + System.IO.Path.GetFileName(file));
                    }
                    // 否则直接Copy文件
                    else
                    {
                        System.IO.File.Copy(file, aimPath + System.IO.Path.GetFileName(file), true);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                //return false;
                throw new Exception(ex.Message);
            }
        }
        private void UploadBop(string path)
        {
            try
            {
                ResultMessage resultMessage = new ResultMessage();
                string uniqueFileName = null;

                if (string.IsNullOrEmpty(path))
                {

                    CopyDir("F:\\相关视频\\新建文件夹", "D:\\jieya");

                    string[] formatArray = { ".zip", ".7z" };
                    (new FastZip()).ExtractZip("D:\\jieya\\fff.zip", "D:\\jieya", "");



                }
            }
            catch (Exception ex)
            {

                throw;
            }
           

        }

        public void jy() 
        {
            GZipStream stream = new GZipStream(new FileStream("", FileMode.Open, FileAccess.ReadWrite), CompressionMode.Decompress);
            FileStream fileStream = new FileStream("", FileMode.OpenOrCreate, FileAccess.Write);
            int data;
            while ((data = stream.ReadByte()) != -1) 
            {
                fileStream.WriteByte((Byte)data);
            }
            fileStream.Close();
            stream.Close();
        }
        /// <summary>
        /// BOM引入模态表格数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public List<BomMainContentListDto> GetBomModelList(string module, string sendTime)
        {
            var userData = _userRepository.GetAll().ToList();
            //.Where(t=>t.Status ==1)
            var query =
             from bomDesignData in _bomDesignrepository.GetAll().Where(s => s.Module != module || s.SendTime != sendTime)
             join materialsContentData in _materialsContentrepository.GetAll()
             on bomDesignData.MaterialsContentId equals
             materialsContentData.Id
             join users in userData on bomDesignData.CreatorUserId equals users.Id into Joinmu
             from mu in Joinmu.DefaultIfEmpty()

             select new BomMainContentListDto
             {
                 Id = bomDesignData.Id,
                 MaterialNo = materialsContentData.MaterialNo,
                 MaterialName = materialsContentData.MaterialName,
                 Model = bomDesignData.Module,
                 VersionNo = bomDesignData.VersionNo,
                 SendTime = bomDesignData.SendTime,
                 CreateUser = mu.Surname + mu.Name,
                 CreationTime = bomDesignData.CreationTime
             };
            if (query != null)
            {
                return query.ToList();
            }
            return new List<BomMainContentListDto>();
        }
        /// <summary>
        /// bom引入保存
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        List<BomDesignDetail> bomDesignDetailsYr = new List<BomDesignDetail>();
        public async Task<ResultMessage> CreateBomCopy(BomEditCopyDto bomEditCopyDto)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                bomDesignDetailsYr.Clear();
                List<BomDesignDetail> bomDesignDetailParents = new List<BomDesignDetail>();
                //循环第一条 芯级 根据id 
                var queryBomDesignDetails = _bomDesignDetailrepository.GetAll().Where(t => t.BomDesignId == bomEditCopyDto.BomIdOld).OrderBy(t => t.LevelNum);
                var queryBomDesign = _bomDesignrepository.FirstOrDefaultAsync(t => t.Id == bomEditCopyDto.BomIdOld).Result;
                if (queryBomDesignDetails != null)
                {
                    bomDesignDetailParents = queryBomDesignDetails.Where(t => t.ParentId == Guid.Empty).ToList();
                    foreach (BomDesignDetail bomDesign in bomDesignDetailParents)
                    {
                        GetBomConformity(bomDesign, bomDesign.Id, bomEditCopyDto.BomIdNew, bomDesignDetailsYr, queryBomDesignDetails.ToList());
                    }
                    if (bomDesignDetailsYr.Count > 0)
                    {
                        //foreach (BomDesignDetail designDetail in bomDesignDetailsYr)
                        //{
                        //    await _bomDesignDetailrepository.InsertAsync(designDetail);
                        //}
                     await   _bomDesignDetailrepository.GetDbContext().BulkInsertAsync(bomDesignDetailsYr);
                    }
                    if (queryBomDesign != null)
                    {
                        _iOperationHistoryAppService.InsertOperationLogNew(bomEditCopyDto.BomIdNew, BusinessTypes.设计bom, OperationTypes.设计bom引入, "【设计bom引入】-->数据来源于型号：" + queryBomDesign.Module + "，发次：" + queryBomDesign.SendTime);
                    }
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        private void GetBomConformity(BomDesignDetail bomDesignDetail, Guid parentGuid, Guid guid, List<BomDesignDetail> bomDesignsList, List<BomDesignDetail> bomDesignDetails)
        {
            Guid parentId = Guid.Empty;
            BomDesignDetail designDetailParent = null;

            List<BomDesignDetail> queryBomDesignDetailChilds = null;
            parentId = bomDesignDetail.Id;
            if (bomDesignDetail.ParentId == Guid.Empty)
            {
                //有子级
                designDetailParent = new BomDesignDetail();
                designDetailParent = bomDesignDetail;
                designDetailParent.BomDesignId = guid;
                //更改芯级的id
                designDetailParent.Id = Guid.NewGuid();
                //添加芯级到集合
                bomDesignsList.Add(designDetailParent);
            }
            //parentId = bomDesignDetail.Id;
            //找对应子级
            if (bomDesignDetail != null)
            {
                queryBomDesignDetailChilds = bomDesignDetails.Where(t => t.ParentId == parentGuid).ToList();
            }
            foreach (BomDesignDetail bomDesign in queryBomDesignDetailChilds)
            {
                parentId = bomDesign.Id;
                BomDesignDetail designDetail = new BomDesignDetail();
                designDetail = bomDesign;
                designDetail.Id = Guid.NewGuid();
                designDetail.BomDesignId = guid;
                designDetail.Status = DocumentStatus.已维护;
                designDetail.ParentId = designDetailParent == null ? bomDesignDetail.Id : designDetailParent.Id;
                bomDesignsList.Add(designDetail);
                GetBomConformity(bomDesign, parentId, guid, bomDesignsList, bomDesignDetails);
            }
        }
        /// <summary>
        /// 节点树的生成
        /// </summary>
        /// <param name="parentNode"></param>
        /// <param name="ParentId"></param>
        List<BomParentTreeDto> bomParentTreeDtoss = new List<BomParentTreeDto>();
        private void BindTree(List<BomParentTreeDto> bomParentTreeDtos, Guid ParentId)
        {
            var queryBom = bomParentTreeDtos.Where(t => t.ParentId == ParentId);
            bomParentTreeDtoss.AddRange(queryBom);
            if (bomParentTreeDtoss != null && bomParentTreeDtoss.Count() > 0)
            {
                for (int i = bomParentTreeDtoss.Count - 1; i >= 0; i--)
                {
                    bomParentTreeDtoss[i].children.AddRange(bomParentTreeDtos.Where(t => t.ParentId == bomParentTreeDtoss[i].Id));
                }
            }
        }
        /// <summary>
        /// bom树加载
        /// </summary>
        /// <returns></returns>
        public List<BomParentTreeDto> GetTreeGrid(Guid ParentId)
        {
            var bomConent = _bomDesignrepository.GetAllIncluding(t => t.BomDesignDetails).Where(d => d.Id == ParentId).FirstOrDefault();
            if (bomConent != null)
            {
                var bomDesignDetailConent = from bomDesignDetail in bomConent.BomDesignDetails.Where(t => t.LevelNum <= 3 && t.BomDesignId == ParentId)
                                            join materalsContent in _materialsContentrepository.GetAll() on bomDesignDetail.MaterialId equals materalsContent.Id
                                            select new BomParentTreeDto
                                            {
                                                Id = bomDesignDetail.Id,
                                                MaterialName = materalsContent.MaterialName,
                                                LevelNum = bomDesignDetail.LevelNum,
                                                ParentId = bomDesignDetail.ParentId,
                                                MaterialId = bomDesignDetail.MaterialId,

                                            };
                BindTree(bomDesignDetailConent.ToList().OrderBy(t => t.LevelNum).ToList(), Guid.Empty);
                return bomParentTreeDtoss;
            }
            return new List<BomParentTreeDto>();
        }
        /// <summary>
        /// bom树子级加载
        /// </summary>
        /// <returns></returns>
        public List<BomParentTreeDto> GetChildTreeGrid(Guid ParentId)
        {
            var queryBomDseign = from querybomDsegnData in _bomDesignDetailrepository.GetAll().Where(t => t.BomDesignId == ParentId).ToList()
                                 join queryMaterialsContent in _materialsContentrepository.GetAll() on querybomDsegnData.MaterialId equals
                                 queryMaterialsContent.Id
                                 where queryMaterialsContent.MaterialProperty.Equals(1)
                                 select new BomParentTreeDto
                                 {
                                     Id = querybomDsegnData.Id,
                                     MaterialName = queryMaterialsContent.MaterialName,
                                     LevelNum = 2
                                 };
            return queryBomDseign.ToList();
        }
        /// <summary>
        /// Bom树数据查看
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<BomMainContentListDto> GetBomModelThreeGrid(GetBomNodeTreeListInput input)
        {
            var userData = _userRepository.GetAll().ToList();
            //根据id获取bomdesignDetail的三级数据
            var querybomDetails = from bomDetail in _bomDesignDetailrepository.GetAll().Where(t => t.ParentId == input.BomId)
                                  join materialsContent in _materialsContentrepository.GetAll().Where(t => t.MaterialProperty == 3) on bomDetail.MaterialId equals materialsContent.Id
                                  join materialsNodesData in _materialsNoderepository.GetAll()
                                  on materialsContent.MaterialsNodeId equals materialsNodesData.Id into Joinbomnm
                                  from mc in Joinbomnm.DefaultIfEmpty()
                                  join users in userData on bomDetail.CreatorUserId equals users.Id into Joinmu
                                  from mu in Joinmu.DefaultIfEmpty()
                                  select new BomMainContentListDto
                                  {
                                      Id = bomDetail.Id,
                                      MaterialNo = materialsContent.MaterialNo,
                                      MaterialName = materialsContent.MaterialName,
                                      Model = materialsContent.Model,
                                      MaterialTypeName = mc.MaterialTypeName,
                                      MaterialSegmentationName = mc.MaterialTypeName,
                                      //VersionNo = bomDesignData.VersionNo,
                                      IsStandard = Enum.Parse(typeof(MaterialsEnum.IsStandard), materialsContent.IsStandard.ToString()).ToString(),
                                      Status = Enum.Parse(typeof(DocumentStatus), bomDetail.Status.ToString()).ToString(),
                                      //SendTime = bc.SendTime,
                                      CreateUser = mu.Surname + mu.Name
                                  };
            return querybomDetails.ToList();
        }
        /// <summary>
        /// 查询Bom主页面信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<BomMainContentListDto>> GetBomList(GetBomContentListInput input)
        {
            var userData = _userRepository.GetAll().ToList();
            //.WhereIf(input.Status >= 0, x => x.Status.Equals(input.Status))
            var query =
               from bomDesignData in _bomDesignrepository.GetAll()
               join materialsContentData in _materialsContentrepository.GetAll().WhereIf(!input.MaterialName.IsNullOrWhiteSpace(), x => x.MaterialName.Contains(input.MaterialName)).WhereIf(!input.MaterialNo.IsNullOrWhiteSpace(), x => x.MaterialNo.Contains(input.MaterialNo))
               on bomDesignData.MaterialsContentId equals
               materialsContentData.Id
               //into JoinbomMc
               //from bc in JoinbomMc.DefaultIfEmpty()
               join materialsNodesData in _materialsNoderepository.GetAll()
                on materialsContentData.MaterialsNodeId equals materialsNodesData.Id into Joinbomnm
               from mc in Joinbomnm.DefaultIfEmpty()
               join materialsNodesData in _materialsNoderepository.GetAll()
               on materialsContentData.MaterialCategoryId equals materialsNodesData.Id into Joinmc
               from mg in Joinmc.DefaultIfEmpty()
               join users in userData on bomDesignData.CreatorUserId equals users.Id into Joinmu
               from mu in Joinmu.DefaultIfEmpty()
               join code in _sysCodeRepository.GetAll().WhereIf(!input.Model.IsNullOrWhiteSpace(), x => x.Description.Contains(input.Model)) on bomDesignData.ModuleId equals code.Id
               //              into codeData
               //from cd in codeData.DefaultIfEmpty()
               join code2 in _sysCodeRepository.GetAll().WhereIf(!input.SendTime.IsNullOrWhiteSpace(), x => x.Description.Contains(input.SendTime)) on bomDesignData.SendTimeId equals code2.Id
               from mt in _makeTaskRepository.GetAll()
               where bomDesignData.ModuleId == mt.ModelId && bomDesignData.SendTimeId == mt.LotNoId
               //            into code2
               //from cd2 in code2.DefaultIfEmpty()
               // where bomDesignData.BomType.StartsWith("3")
               select new BomMainContentListDto
               {
                   Id = bomDesignData.Id,
                   MaterialNo = materialsContentData.MaterialNo,
                   MaterialName = materialsContentData.MaterialName,
                   Model = code.Description,
                   MaterialTypeName = "整装",
                   MaterialSegmentationName = mc.MaterialTypeName,
                   MaterialProperty = code.Description,
                   VersionNo = bomDesignData.VersionNo,
                   IsStandard = Enum.Parse(typeof(MaterialsEnum.IsStandard), materialsContentData.IsStandard.ToString()).ToString(),
                   Status = Enum.Parse(typeof(DocumentStatus), bomDesignData.Status.ToString()).ToString(),
                   SendTime = code2.Description,
                   RocketState = mt.RocketState,
                   CreateUser = mu.Surname + mu.Name,
                   CreationTime = bomDesignData.CreationTime
               };
            if (query != null)
            {
                var queryBomContentDataList = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();
                return new PagedResultDto<BomMainContentListDto>(query.Count(), queryBomContentDataList);
            }
            return new PagedResultDto<BomMainContentListDto>();
        }
        /// <summary>
        /// 新增Bom父级物料选择模态框 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<BomMainSelectParentContentListDto>> GetSelectParentMaterials(GetMaterialListInput input)
        {
            try
            {
                var query = from materialsContent in _materialsContentrepository.GetAll().Where(t => t.MaterialProperty == 0)
                            join matgerialsNode in _materialsNoderepository.GetAll()
                            on materialsContent.MaterialsNodeId equals matgerialsNode.Id
                            into Joinnc
                            from bm in Joinnc.DefaultIfEmpty()
                            join materialsNode2 in _materialsNoderepository.GetAll()
                            on materialsContent.MaterialCategoryId equals materialsNode2.Id
                            into Joinmn
                            from mn in Joinmn.DefaultIfEmpty()
                            join code in _sysCodeRepository.GetAll() on materialsContent.UnitId equals code.Id
                               into codeData
                            from cd in codeData.DefaultIfEmpty()
                            join code2 in _sysCodeRepository.GetAll() on materialsContent.ModelId equals code2.Id
                                        into codeData2
                            from cd2 in codeData2.DefaultIfEmpty()
                            join code3 in _sysCodeRepository.GetAll() on materialsContent.SendTimeId equals code3.Id
                            into codeData3
                            from cd3 in codeData3.DefaultIfEmpty()
                                //join bomDesignData in _bomDesignrepository.GetAll()
                                //on materialsContent.Id equals bomDesignData.MaterialsContentId
                                //into Joindm
                                //from dm in Joindm.DefaultIfEmpty()
                                //join bomdesignDetailData in _bomDesignDetailrepository.GetAll()
                                //on dm.Id equals bomdesignDetailData.BomDesignId
                                //into Joinbd
                                //from bd in Joinbd.DefaultIfEmpty()
                                //    //排除状态为1:已维护:2:审核中 || materialsContent.MaterialProperty.Equals(1)
                            where (materialsContent.MaterialProperty.Equals((int)MaterialsEnum.MaterialProperty.整装) || materialsContent.MaterialProperty.Equals((int)MaterialsEnum.MaterialProperty.部件) || materialsContent.MaterialProperty.Equals((int)MaterialsEnum.MaterialProperty.组件))
                            select new BomMainSelectParentContentListDto
                            {
                                Id = materialsContent.Id,
                                MaterialTypeId = materialsContent.MaterialsNodeId,
                                MaterialNo = materialsContent.MaterialNo,
                                MaterialName = materialsContent.MaterialName,
                                Model = cd2.Description,
                                MaterialTypeName = bm.MaterialTypeName,
                                MaterialSegmentationName = mn.MaterialTypeName,
                                IsKeyPart = Enum.Parse(typeof(MaterialsEnum.IsKeyPart), materialsContent.IsKeyPart.ToString()).ToString(),
                                DrawingNo = materialsContent.DrawingNo,
                                // Unit1BomDosage = bd.Unit1BomDosage,
                                UnitId = materialsContent.UnitId,
                                UnitName = cd.Description,
                                Remark = materialsContent.Remark,
                                Attribute = materialsContent.MaterialProperty,
                                SendTime = cd3.Description,
                                ModelId = materialsContent.ModelId,
                                SendTimeId = materialsContent.SendTimeId
                            };
                if (query != null)
                {
                    var materialsContentDataList = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();
                    return new PagedResultDto<BomMainSelectParentContentListDto>(query.Count(), materialsContentDataList.ToList());
                }
            }
            catch
            {
                throw new UserFriendlyException("内部错误");
            }
            return new PagedResultDto<BomMainSelectParentContentListDto>();
        }
        /// <summary>
        /// 新增子级模态框
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<BomMainSelectParentContentListDto>> GetSelectChildMaterials(GetMaterialListInput input)
        {
            try
            {
                //找出物料类型不是一级和二级的物料
                var queryMaterialsContent = (from materialsContent in _materialsContentrepository.GetAll().Where(t => t.MaterialProperty == input.MaterialPropertyBs)
                                             join materialsNode in _materialsNoderepository.GetAll() on materialsContent.MaterialsNodeId equals materialsNode.Id into mm
                                             from Joinmm in mm.DefaultIfEmpty()
                                             join materialsNodeSegmentation in _materialsNoderepository.GetAll() on materialsContent.MaterialCategoryId equals materialsNodeSegmentation.Id
                                             into mn
                                             from Joinmn in mn.DefaultIfEmpty()
                                             join bomDesign in _bomDesignrepository.GetAll() on materialsContent.Id equals bomDesign.MaterialsContentId
                                             into bm
                                             from Joinbm in bm.DefaultIfEmpty()
                                             join code in _sysCodeRepository.GetAll() on materialsContent.UnitId equals code.Id
                                               into codeData
                                             from cd in codeData.DefaultIfEmpty()
                                             join code2 in _sysCodeRepository.GetAll() on materialsContent.ModelId equals code2.Id
                                            into codeData2
                                             from cd2 in codeData2.DefaultIfEmpty()
                                             join code3 in _sysCodeRepository.GetAll() on materialsContent.SendTimeId equals code3.Id
                                             into codeData3
                                             from cd3 in codeData3.DefaultIfEmpty()
                                             select new BomMainSelectParentContentListDto
                                             {
                                                 MaterialTypeId = materialsContent.Id,
                                                 MaterialNo = materialsContent.MaterialNo,
                                                 MaterialName = materialsContent.MaterialName,
                                                 MaterialProperty = materialsContent.MaterialProperty,
                                                 Model = materialsContent.Model,
                                                 MaterialTypeName = Joinmm.MaterialTypeName,
                                                 MaterialSegmentationName = Joinmn.MaterialTypeName,
                                                 VersionNo = Joinbm.VersionNo,
                                                 UnitId = materialsContent.UnitId,
                                                 IsKeyPart = Enum.Parse(typeof(MaterialsEnum.IsKeyPart), materialsContent.IsKeyPart.ToString()).ToString(),
                                                 Remark = materialsContent.Remark,
                                                 Attribute = materialsContent.MaterialProperty,
                                                 UnitName = cd.Code,
                                                 Id = materialsContent.Id,
                                                 SendTime = cd3.Description,
                                                 IsUsed = Enum.Parse(typeof(MaterialsEnum.UsedIs), materialsContent.IsUsed.ToString()).ToString(),
                                                 CreationTime = materialsContent.CreationTime


                                             })
                                             .WhereIf(!string.IsNullOrEmpty(input.MaterialNo), d => d.MaterialNo.Contains(input.MaterialNo)) //add 11/30
                                             .WhereIf(!string.IsNullOrEmpty(input.MaterialName), d => d.MaterialName.Contains(input.MaterialName)) //add 11/30
                                             .OrderByDescending(t => t.CreationTime);
                if (queryMaterialsContent != null)
                {
                    var materialsContentDataList = await queryMaterialsContent.PageBy(input).ToListAsync();
                    return new PagedResultDto<BomMainSelectParentContentListDto>(queryMaterialsContent.Count(), materialsContentDataList);
                }
            }
            catch (Exception)
            {
                throw new UserFriendlyException("内部错误");
            }
            return new PagedResultDto<BomMainSelectParentContentListDto>();
        }
        /// <summary>
        /// 新增物料子级模态框
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<BomMainSelectParentContentListDto>> GetSelectChildMaterialsContent(GetMaterialListInput input)
        {
            try
            {
                //找出物料类型不是一级和二级的物料
                var queryMaterialsContent = (from materialsContent in _materialsContentrepository.GetAll().Where(t => t.MaterialProperty == input.MaterialPropertyBs)
                                            .WhereIf(!string.IsNullOrEmpty(input.MaterialNo), d => d.MaterialNo == input.MaterialNo)
                                            .WhereIf(!string.IsNullOrEmpty(input.MaterialName), d => d.MaterialName == input.MaterialName)
                                             join materialsNode in _materialsNoderepository.GetAll() on materialsContent.MaterialsNodeId equals materialsNode.Id into mm
                                             from Joinmm in mm.DefaultIfEmpty()
                                             join materialsNodeSegmentation in _materialsNoderepository.GetAll() on materialsContent.MaterialCategoryId equals materialsNodeSegmentation.Id
                                             into mn
                                             from Joinmn in mn.DefaultIfEmpty()
                                             join bomDesign in _bomDesignrepository.GetAll() on materialsContent.Id equals bomDesign.MaterialsContentId
                                             into bm
                                             from Joinbm in bm.DefaultIfEmpty()
                                             join code in _sysCodeRepository.GetAll() on materialsContent.UnitId equals code.Id
                     into codeData
                                             from cd in codeData.DefaultIfEmpty()
                                             select new BomMainSelectParentContentListDto
                                             {
                                                 Id = materialsContent.Id,
                                                 MaterialTypeId = Joinmm.Id,
                                                 MaterialNo = materialsContent.MaterialNo,
                                                 MaterialName = materialsContent.MaterialName,
                                                 Model = materialsContent.Model,
                                                 MaterialTypeName = Joinmm.MaterialTypeName,
                                                 MaterialSegmentationName = Joinmn.MaterialTypeName,
                                                 VersionNo = Joinbm.VersionNo,
                                                 UnitId = materialsContent.UnitId,
                                                 IsKeyPart = Enum.Parse(typeof(MaterialsEnum.IsKeyPart), materialsContent.IsKeyPart.ToString()).ToString(),
                                                 Remark = materialsContent.Remark,
                                                 UnitName = cd.Code,
                                                 MaterialProperty = materialsContent.MaterialProperty
                                             })
                                             .WhereIf(!string.IsNullOrEmpty(input.MaterialNo), d => d.MaterialNo == input.MaterialNo) //add 11/30
                                             .WhereIf(!string.IsNullOrEmpty(input.MaterialName), d => d.MaterialName == input.MaterialName); //add 11/30;
                if (queryMaterialsContent != null)
                {
                    var materialsContentDataList = await queryMaterialsContent.PageBy(input).ToListAsync();
                    return new PagedResultDto<BomMainSelectParentContentListDto>(queryMaterialsContent.Count(), materialsContentDataList);
                }
            }
            catch (Exception)
            {
                throw new UserFriendlyException("内部错误");
            }
            return new PagedResultDto<BomMainSelectParentContentListDto>();
        }
        /// <summary>
        /// 删除bom
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultMessage> DeleBomNode(Guid id)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var bomDesignDetailList = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == id).Result;
                if (bomDesignDetailList.CreatorUserId != GetCurrentUser().Id) //add 11/30
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "非本人创建，不能删除！!";
                    return resultMessage;
                    //throw new UserFriendlyException("非本人创建，不能删除！");
                }
                if (bomDesignDetailList != null)
                {
                    var bomDesignChildDetailList = _bomDesignDetailrepository.GetAll().Where(t => t.ParentId == bomDesignDetailList.Id);
                    if (bomDesignChildDetailList.Count() > 0)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = "请先删除子级!";
                        return resultMessage;
                        //throw new UserFriendlyException("请先删除子级");
                    }
                    await _bomDesignDetailrepository.DeleteAsync(t => t.Id == id);
                    var queryMaterials = _materialsContentrepository.FirstOrDefaultAsync(t => t.Id == bomDesignDetailList.MaterialId).Result;
                    _iOperationHistoryAppService.InsertOperationLogNew(bomDesignDetailList.BomDesignId, BusinessTypes.设计bom, OperationTypes.设计bom删除子级, "删除bom:" + queryMaterials.MaterialName);
                }
                else
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "无对应BOM数据!";
                    return resultMessage;
                    //throw new UserFriendlyException("无对应BOM数据!");
                }
                //var bomDesignlist = _bomDesignrepository.GetAll().Where(t => t.Id == guid);
                //if (bomDesignlist.Count() > 0)
                //{
                //    await _bomDesignrepository.DeleteAsync(guid);
                //}
                //else
                //{
                //    throw new UserFriendlyException("无对应BOM数据!");
                //}
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 新增bom/维护bom
        /// </summary>
        /// <param name="bomEditList"></param>
        /// <returns></returns>
        public async Task<ResultMessage> AddOrUpBomList(BomEditList bomEditList)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                if (bomEditList != null)
                {
                    if (bomEditList.children.Count == 0 && bomEditList.data != null)
                    {
                        var fccount = _bomDesignrepository.Count(t => t.ModuleId == bomEditList.data.ModelId && t.SendTimeId == bomEditList.data.SendTimeId);
                        if (fccount == 0)
                        {
                            var moduleResult = _sysCodeRepository.FirstOrDefaultAsync(t => t.Id == bomEditList.data.ModelId).Result;
                            var sendTimeResult = _sysCodeRepository.FirstOrDefaultAsync(t => t.Id == bomEditList.data.SendTimeId).Result;
                            if (moduleResult == null || sendTimeResult == null) { throw new UserFriendlyException("不存在该型号或发次请核对！"); }
                            BomDesign bomDesign = new BomDesign
                            {
                                MaterialsContentId = bomEditList.data.MaterialsContentId,
                                BomType = bomEditList.data.BomType,
                                VersionNo = bomEditList.data.VersionNo,
                                IsUsed = bomEditList.data.IsUsed,
                                ChangeId = bomEditList.data.ChangeId,
                                Status = (int)DocumentStatus.待维护,
                                Id = Guid.NewGuid(),
                                Module = bomEditList.data.Model,
                                SendTime = bomEditList.data.SendTime,
                                ModuleId = moduleResult.Id,
                                SendTimeId = sendTimeResult.Id
                            };
                            await _bomDesignrepository.InsertAsync(bomDesign);
                        }
                        else
                        {
                            resultMessage.code = 1;
                            resultMessage.Message = "此型号、发次已添加无须重复添加！";
                            return resultMessage;
                            //throw new UserFriendlyException("此型号、发次已添加无须重复添加！");
                        }
                        resultMessage.code = 0;
                        return resultMessage;
                    }
                    //新增bom
                    if (bomEditList.data.Bs == (int)BomEnum.BomBs.保存)
                    {
                        bomEditList.data.Status = (int)DocumentStatus.已维护;
                        BomDesignDetail bomDesignDetail = new BomDesignDetail();
                        foreach (BomDetaillist bomDetaillist in bomEditList.children)
                        {
                            if (bomDetaillist == null)
                            {
                                resultMessage.code = 1;
                                resultMessage.Message = "请确认物料建模信息是否存在！";
                                return resultMessage;
                                //throw new UserFriendlyException("请确认物料建模信息是否存在！");
                            }
                            await operation(bomEditList, bomDetaillist, bomDesignDetail);

                        }
                    }
                    //新增bom
                    else if (bomEditList.data.Bs == (int)BomEnum.BomBs.保存并送审)
                    {
                        bomEditList.data.Status = (int)DocumentStatus.已维护;
                        BomDesignDetail bomDesignDetail = new BomDesignDetail();
                        foreach (BomDetaillist bomDetaillist in bomEditList.children)
                        {
                            await operation(bomEditList, bomDetaillist, bomDesignDetail);
                            _iOperationHistoryAppService.InsertOperationLog(bomEditList.data.MaterialsContentId, 2, 13, bomEditList.data.MaterialName);
                        }
                    }
                    //维护bom 
                    else if (bomEditList.data.Bs == (int)BomEnum.BomBs.BOM维护保存并送审)
                    {
                        // await DeleBom(bomEditList.data.Id);
                        bomEditList.data.Status = (int)DocumentStatus.待维护;
                        BomDesignDetail bomDesignDetail = new BomDesignDetail();
                        foreach (BomDetaillist bomDetaillist in bomEditList.children)
                        {
                            //如果需要修改二级节点 不同用户不能修改
                            var userData = _userRepository.GetAll().ToList()[0];
                            var bomRole = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == bomDetaillist.data.Id).Result;
                            if (bomRole == null)
                            {
                                resultMessage.code = 1;
                                resultMessage.Message = "该发次bom节点异常";
                                return resultMessage;
                                //throw new UserFriendlyException("该发次bom节点异常");
                            }
                            if (bomRole.CreatorUserId != GetCurrentUser().Id) //add 11/30
                            {
                                resultMessage.code = 1;
                                resultMessage.Message = "非本人创建，不能修改！";
                                return resultMessage;
                                //throw new UserFriendlyException("非本人创建，不能修改！");
                            }
                            await operation(bomEditList, bomDetaillist, bomDesignDetail);
                        }
                    }
                }
                try
                {
                    if (bomEditLists.Count > 0)
                    {
                        foreach (BomDesign design in bomEditLists)
                        {
                            await _bomDesignrepository.InsertAsync(design);
                            _iOperationHistoryAppService.InsertOperationLog(design.Id, 2, 11, "新增发次");
                        };
                        bomEditLists.Clear();
                    }
                    Guid logid = Guid.Empty;
                    if (bomdetaillists.Count > 0)
                    {
                        foreach (BomDesignDetail designDetail in bomdetaillists)
                        {
                            logid = designDetail.BomDesignId;
                            await _bomDesignDetailrepository.InsertAsync(designDetail);
                        };
                        //新增履历 
                        var queryBomMaterials = from bomMaterialsData in _materialsContentrepository.GetAll() join bomData in bomdetaillists on bomMaterialsData.Id equals bomData.MaterialId select bomMaterialsData;
                        foreach (var queryData in queryBomMaterials)
                        {
                            _iOperationHistoryAppService.InsertOperationLog(logid, 2, 11, "新增：" + queryData.MaterialName);
                        }
                        bomdetaillists.Clear();
                    }
                }
                catch (Exception ex)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "内部错误";
                    return resultMessage;
                    //throw new UserFriendlyException("内部错误");
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        private async Task operation(BomEditList bomEditList, BomDetaillist bomdetaillist, BomDesignDetail bomDesignDetails)
        {
            BomDesignDetail bomDesignDetail = null;
            BomDesign bomDesign = new BomDesign();
            Guid guid = bomdetaillist.data.MaterialId;
            MaterialsContent querybomEditList = null;
            if (bomEditList.data.InsertBs == 0)
            {
                //根据物料详细id 查询物料详细表有无数据
                querybomEditList = await _materialsContentrepository.FirstOrDefaultAsync(t => t.Id == bomEditList.data.MaterialsContentId);
            }
            else
            {
                querybomEditList = await _materialsContentrepository.FirstOrDefaultAsync(t => t.Id == bomdetaillist.data.MaterialId);
            }
            //根据入参id 查询 如果 有数据证明 再判断 BomDesing表中有没有该条数据 如果有放弃，无则新增
            //var query = _materialsContentrepository.FirstOrDefaultAsync(t => t.Id == guid).Result;
            //判断materialsContent中 物料类型如果是  如果是0 并且 bom主表没有数据 那就新增 （0 组件,1 部件,2 零件）
            if (querybomEditList != null)
            {
                if (querybomEditList.MaterialProperty == 0)
                {
                    //判断主表中是否存在 每个发次的bom只能添加一次
                    var bomDesingCount = await _bomDesignrepository.FirstOrDefaultAsync(t => t.MaterialsContentId == querybomEditList.Id);
                    if (bomDesingCount != null)
                    {
                        throw new UserFriendlyException("此型号、发次已添加无须重复添加！");
                    }
                    var moduleResult = _sysCodeRepository.FirstOrDefaultAsync(t => t.Id == bomEditList.data.ModelId).Result;
                    var sendTimeResult = _sysCodeRepository.FirstOrDefaultAsync(t => t.Id == bomEditList.data.SendTimeId).Result;
                    if (moduleResult == null || sendTimeResult == null)
                    {
                        throw new UserFriendlyException("请确认该型号发次是否和字典对应");
                    }
                    if (bomDesingCount == null && bomEditList.data.InsertBs == 0)
                    {
                        bomDesign.MaterialsContentId = bomEditList.data.MaterialsContentId;
                        bomDesign.BomType = bomEditList.data.BomType;
                        //bomDesign.VersionNo = bomEditList.data.VersionNo;
                        bomDesign.IsUsed = bomEditList.data.IsUsed;
                        bomDesign.ChangeId = bomEditList.data.ChangeId;
                        bomDesign.Status = bomEditList.data.Status;
                        bomDesign.Id = Guid.NewGuid();
                        bomDesign.Module = bomEditList.data.Model;
                        bomDesign.ModuleId = moduleResult.Id;
                        bomDesign.SendTimeId = sendTimeResult.Id;
                        bomDesign.SendTime = bomEditList.data.SendTime;
                        bomEditLists.Add(bomDesign);
                        BomGuid = bomDesign.Id;
                        bomDesign.Status = (int)DocumentStatus.已维护;

                    }
                    else
                    {
                        if (bomEditList.data.Bs == 2)
                        {
                            //用于更新bom
                            var bomDesingCountUpdate = _bomDesignrepository.FirstOrDefaultAsync(t => t.Id == bomEditList.data.Id).Result;
                            if (bomDesingCountUpdate != null) { BomGuid = bomDesingCountUpdate.Id; } else { throw new UserFriendlyException("没查询到bom主表相关信息"); }
                        }
                        else
                        {
                            BomGuid = bomDesingCount.Id;
                        }
                    }
                }
                //如果是芯级
                if (bomdetaillist.data.Attribute == 1)
                {
                    if (bomdetaillist.data.ParentId == Guid.Empty)
                    {
                        var designDetailData = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.LevelNum == 2 && t.BomDesignId == BomGuid && t.MaterialId == bomdetaillist.data.MaterialId).Result;
                        if (designDetailData != null)
                        {
                            bomDesignDetail = designDetailData;
                        }
                    }
                }
                if (bomDesignDetail == null)
                {
                    //如果是物料不是一级 那就是添加到 bom详细
                    bomDesignDetail = new BomDesignDetail
                    {
                        BomDesignId = BomGuid,
                        MaterialId = bomdetaillist.data.MaterialId,
                        ParentMaterialId = bomdetaillist.data.MaterialId,
                        //   ParentId = bomDesignDetails.Id == Guid.Empty ? bomDesignDetails.Id:BomGuid,//bom_design_detail.id
                        ParentId = bomDesignDetails.Id,//bom_design_detail.id
                        Unit1BomDosage = bomdetaillist.data.Unit1BomDosage,
                        LevelRelationship = bomdetaillist.data.LevelRelationship,
                        LevelNum = (bomDesignDetails.LevelNum + 1),
                        Id = Guid.NewGuid(),
                        OrderNum = bomDesignDetails.OrderNum + 1,
                        Status = DocumentStatus.已维护,
                        MaterialProperty = bomdetaillist.data.Attribute

                    };
                    bomdetaillists.Add(bomDesignDetail);
                }
                if (bomdetaillist.children.Count > 0)
                {
                    for (var i = bomdetaillist.children.Count - 1; i >= 0; i--)
                    {
                        bomEditList.children = bomdetaillist.children;
                        //用于新增和更新的区分 后期可去掉 更新的相关内容
                        bomEditList.data.InsertBs = 1;
                        await operation(bomEditList, bomdetaillist.children[i], bomDesignDetail);
                    }
                }
            }
        }
        /// <summary>
        /// 更新bom用量
        /// </summary>
        /// <param name="input"></param>
        /// <param name=""></param>
        /// <returns></returns>
        public async Task UpdateChildrenNode(BomDesignDetailDto input)
        {
            if (input != null)
            {
                var queryBomDesignDetail = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == input.Id).Result;
                if (queryBomDesignDetail.CreatorUserId != GetCurrentUser().Id)
                {
                    throw new UserFriendlyException("非本人创建，没有修改该数据的权限！");
                }
                queryBomDesignDetail.Unit1BomDosage = input.Unit1BomDosage;
                queryBomDesignDetail.Remark = input.Remark;
                queryBomDesignDetail.YearsNo = input.YearsNo;
                await _bomDesignDetailrepository.UpdateAsync(queryBomDesignDetail);
                var queryMaterials = _materialsContentrepository.FirstOrDefaultAsync(t => t.Id == input.MaterialId).Result;
                _iOperationHistoryAppService.InsertOperationLog(input.BomDesignId, 2, 12, "更新bom" + queryMaterials.MaterialName + "用量:" + input.Unit1BomDosage);
                //_iOperationHistoryAppService.InsertOperationLog(logId, 2, 12, "更新bom用量：" + queryData.MaterialName);
            }
                await UpdateStatus(input);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input">新增的数据</param>
        /// <param name="guid">点击行的id</param>
        /// <returns></returns>
        public async Task<BomDetaillist> CreateChildrenNode(List<BomDesignDetailDto> input, Guid guid)
        {
            var userData = _userRepository.GetAll().ToList();
            BomDetaillist resultMessage = new BomDetaillist();
            resultMessage.children = new List<BomDetaillist>();
            resultMessage.children.Clear();
            try
            {
                BomDesignDetailDto bomDesignDetailDto = new BomDesignDetailDto();
                int count = 0;
                Guid btid = Guid.Empty;
                Guid bomDesignId = Guid.Empty;
                int orderNum = 0;
                if (input != null)
                {
                    var queryBomDesignDetail = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == guid).Result;
                    if (queryBomDesignDetail.CreatorUserId != GetCurrentUser().Id) //add 11/30
                    {
                        throw new UserFriendlyException("非本人创建，没有新增该数据的权限！");
                    }
                    if (input.Count > 1)
                    {

                        if (queryBomDesignDetail != null)
                        {
                            for (int i = 0; i <= input.Count - 1; i++)
                            {
                                //后期去掉
                                var materalsContentResult = _materialsContentrepository.FirstOrDefaultAsync(t => t.Id == input[i].MaterialId).Result;
                                if (materalsContentResult.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件)
                                {
                                    var zjResult = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == guid).Result;


                                    //找出全部零件的数量
                                    var ljList = _bomDesignDetailrepository.GetAll().Where(t => t.LevelRelationship.StartsWith(zjResult.LevelRelationship) && t.BomDesignId == zjResult.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件);
                                    if (ljList != null && ljList.Count() > 0)
                                    {
                                        orderNum = ljList.OrderByDescending(t => t.OrderNum).First().OrderNum;
                                    }
                                    //找出全部组件的数量
                                    var zjList = _bomDesignDetailrepository.GetAll().Where(t => t.LevelRelationship.StartsWith(zjResult.LevelRelationship) && t.BomDesignId == zjResult.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件 && t.ParentId == zjResult.Id);
                                    //循环找出组件下的零件数量汇总
                                    int zjChildCount = 0;
                                    foreach (BomDesignDetail bomDesignDetail in zjList)
                                    {
                                        var lj = _bomDesignDetailrepository.GetAll().Where(t => t.ParentId == bomDesignDetail.Id).Count();
                                        zjChildCount += lj;
                                    }
                                    int ljCount = ljList.Count();
                                    //全部零件数量 减去 零件汇总 +组件的数量
                                    int subtractionCount = ljCount - zjChildCount + zjList.Count() + 1;

                                    BomDesignDetail ZjbomDesignDetail = new BomDesignDetail
                                    {
                                        MaterialId = input[i].MaterialId,
                                        ParentMaterialId = input[i].ParentMaterialId,
                                        ParentId = guid,
                                        LevelNum = queryBomDesignDetail.LevelNum + 1,
                                        Unit1BomDosage = input[i].Unit1BomDosage,
                                        BomDesignId = queryBomDesignDetail.BomDesignId,
                                        LevelRelationship = queryBomDesignDetail.LevelRelationship + "." + subtractionCount,
                                        Status = (DocumentStatus)0,
                                        MaterialProperty = (int)MaterialsEnum.MaterialProperty.零件,
                                        OrderNum = orderNum + 1
                                    };
                                    Guid returnId = Guid.Empty;
                                    returnId = await _bomDesignDetailrepository.InsertAndGetIdAsync(ZjbomDesignDetail);
                                    _unitOfWorkManager.Current.SaveChanges();
                                    var bomList = _bomDesignDetailrepository.GetAll().Where(t => t.Id == returnId).ToList();
                                    var queryBomDetailLsit = (from bomdetaillistTwo in bomList
                                                              join materialasContent in _materialsContentrepository.GetAll() on bomdetaillistTwo.MaterialId equals materialasContent.Id
                                                              join matialsNode in _materialsNoderepository.GetAll() on materialasContent.MaterialsNodeId equals matialsNode.Id
                                                              join matialsNodeTwo in _materialsNoderepository.GetAll() on materialasContent.MaterialCategoryId equals matialsNodeTwo.Id
                                                               into JoinmuCate
                                                              from muc in JoinmuCate.DefaultIfEmpty()
                                                              join code in _sysCodeRepository.GetAll() on materialasContent.UnitId equals code.Id
                       into codeData
                                                              from cd in codeData.DefaultIfEmpty()
                                                              join userParentData in userData on bomdetaillistTwo.CreatorUserId equals userParentData.Id into Joinmu
                                                              from mu in Joinmu.DefaultIfEmpty()
                                                              select new BomDetaillist
                                                              {
                                                                  data = new BomEditChildData
                                                                  {
                                                                      BomDesignId = bomdetaillistTwo.BomDesignId,
                                                                      MaterialId = bomdetaillistTwo.MaterialId,
                                                                      ParentMaterialId = bomdetaillistTwo.ParentMaterialId,
                                                                      Unit1BomDosage = bomdetaillistTwo.Unit1BomDosage,
                                                                      MaterialName = materialasContent.MaterialName,
                                                                      LevelRelationship = bomdetaillistTwo.LevelRelationship,
                                                                      MaterialNo = materialasContent.MaterialNo,
                                                                      Id = bomdetaillistTwo.Id,
                                                                      LevelNum = bomdetaillistTwo.LevelNum,
                                                                      MaterialTypeName = matialsNode.MaterialTypeName,
                                                                      Model = materialasContent.Model,
                                                                      Remark = materialasContent.Remark,
                                                                      MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialasContent.MaterialProperty.ToString()).ToString(),
                                                                      MaterialSegmentationName = muc==null?"": muc.MaterialTypeName,
                                                                      CreateUserName = mu == null ? "" : mu.Surname + mu.Name,
                                                                      Status = -1,
                                                                      CreateTime = bomdetaillistTwo.CreationTime,
                                                                      VersionNo = bomdetaillistTwo.VersionNo,
                                                                      // Btid = input.BomId,
                                                                      OrderNum = bomdetaillistTwo.OrderNum,
                                                                      UnitName = cd==null?"":cd.Description
                                                                  },
                                                                  children = new List<BomDetaillist>()
                                                              }).OrderBy(t => t.data.OrderNum).ToList();
                                    //var bomDetailContent = ObjectMapper.Map<List<BomDesignDetailDto>>(bomList);
                                    if (queryBomDetailLsit.Count > 0)
                                    {
                                        resultMessage.children.AddRange(queryBomDetailLsit);
                                    }
                                }
                                else if (materalsContentResult.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件)
                                {
                                    int withinComponent = 0;

                                    var materalsContent = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.MaterialId == input[i].MaterialId && t.BomDesignId == queryBomDesignDetail.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件 && t.Id == queryBomDesignDetail.ParentId).Result;
                                    if (materalsContent == null)
                                    {
                                        var zjResult = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == guid).Result;
                                        //找出全部零件的数量
                                        var ljList = _bomDesignDetailrepository.GetAll().Where(t => t.LevelRelationship.StartsWith(zjResult.LevelRelationship) && t.BomDesignId == zjResult.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件);
                                        if (ljList != null && ljList.Count() > 0)
                                        {
                                            orderNum = ljList.OrderByDescending(t => t.OrderNum).First().OrderNum;
                                        }
                                        //找出全部组件的数量
                                        var zjList = _bomDesignDetailrepository.GetAll().Where(t => t.LevelRelationship.StartsWith(zjResult.LevelRelationship) && t.BomDesignId == zjResult.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件 && t.ParentId == zjResult.Id);
                                        //循环找出组件下的零件数量汇总
                                        int zjChildCount = 0;
                                        foreach (BomDesignDetail bomDesignDetail in zjList)
                                        {
                                            var lj = _bomDesignDetailrepository.GetAll().Where(t => t.ParentId == bomDesignDetail.Id).Count();
                                            zjChildCount += lj;
                                        }
                                        int ljCount = ljList.Count();
                                        //全部零件数量 减去 零件汇总 +组件的数量
                                        int subtractionCount = ljCount - zjChildCount + zjList.Count() + 1;
                                        BomDesignDetail btContent = null;
                                        int zjcount = 0;
                                        //找出父级
                                        btContent = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == queryBomDesignDetail.ParentId).Result;
                                        //针对于组件下的组件
                                        if (queryBomDesignDetail.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件)
                                        {
                                            //找出组件下所有的组件
                                            var zjChildList = _bomDesignDetailrepository.GetAll().Where(t => t.LevelRelationship.StartsWith(queryBomDesignDetail.LevelRelationship) && t.BomDesignId == queryBomDesignDetail.BomDesignId);
                                            withinComponent = -2;
                                            BomDesignDetail bomDesignDetail = new BomDesignDetail
                                            {
                                                MaterialId = input[i].MaterialId,
                                                ParentMaterialId = btContent.ParentMaterialId,
                                                ParentId = guid,
                                                LevelNum = queryBomDesignDetail.LevelNum + 1,
                                                Unit1BomDosage = input[i].Unit1BomDosage,
                                                BomDesignId = queryBomDesignDetail.BomDesignId,
                                                WithinComponent = withinComponent,
                                                LevelRelationship = queryBomDesignDetail.LevelRelationship + "." + subtractionCount,
                                                Status = (DocumentStatus)4,
                                                MaterialProperty = (int)MaterialsEnum.MaterialProperty.组件,
                                                OrderNum = orderNum + 1

                                            };
                                            Guid returnId = Guid.Empty;
                                            returnId = await _bomDesignDetailrepository.InsertAndGetIdAsync(bomDesignDetail);
                                            _unitOfWorkManager.Current.SaveChanges();
                                            var bomList = _bomDesignDetailrepository.GetAll().Where(t => t.Id == returnId).ToList();
                                            var queryBomDetailLsit = (from bomdetaillistTwo in bomList
                                                                      join materialasContent in _materialsContentrepository.GetAll() on bomdetaillistTwo.MaterialId equals materialasContent.Id
                                                                      join matialsNode in _materialsNoderepository.GetAll() on materialasContent.MaterialsNodeId equals matialsNode.Id
                                                                      join matialsNodeTwo in _materialsNoderepository.GetAll() on materialasContent.MaterialCategoryId equals matialsNodeTwo.Id
                                                             into JoinmuCate
                                                                      from muc in JoinmuCate.DefaultIfEmpty()
                                                                      join code in _sysCodeRepository.GetAll() on materialasContent.UnitId equals code.Id
                  into codeData
                                                                      from cd in codeData.DefaultIfEmpty()
                                                                      join userParentData in userData on bomdetaillistTwo.CreatorUserId equals userParentData.Id into Joinmu
                                                                      from mu in Joinmu.DefaultIfEmpty()
                                                                      select new BomDetaillist
                                                                      {
                                                                          data = new BomEditChildData
                                                                          {
                                                                              BomDesignId = bomdetaillistTwo.BomDesignId,
                                                                              MaterialId = bomdetaillistTwo.MaterialId,
                                                                              ParentMaterialId = bomdetaillistTwo.ParentMaterialId,
                                                                              Unit1BomDosage = bomdetaillistTwo.Unit1BomDosage,
                                                                              MaterialName = materialasContent.MaterialName,
                                                                              LevelRelationship = bomdetaillistTwo.LevelRelationship,
                                                                              MaterialNo = materialasContent.MaterialNo,
                                                                              Id = bomdetaillistTwo.Id,
                                                                              LevelNum = bomdetaillistTwo.LevelNum,
                                                                              MaterialTypeName = matialsNode.MaterialTypeName,
                                                                              Model = materialasContent.Model,
                                                                              Remark = materialasContent.Remark,
                                                                              MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialasContent.MaterialProperty.ToString()).ToString(),
                                                                              MaterialSegmentationName = muc == null ? "" : muc.MaterialTypeName,
                                                                              CreateUserName = mu == null ? "" : mu.Surname + mu.Name,
                                                                              Status = -1,
                                                                              CreateTime = bomdetaillistTwo.CreationTime,
                                                                              VersionNo = bomdetaillistTwo.VersionNo,
                                                                              // Btid = input.BomId,
                                                                              OrderNum = bomdetaillistTwo.OrderNum,
                                                                              UnitName = cd == null ? "" : cd.Description
                                                                          },
                                                                          children = new List<BomDetaillist>()
                                                                      }).OrderBy(t => t.data.OrderNum).ToList();
                                            //var bomDetailContent = ObjectMapper.Map<List<BomDesignDetailDto>>(bomList);
                                            if (queryBomDetailLsit.Count > 0)
                                            {
                                                resultMessage.children.AddRange(queryBomDetailLsit);
                                            }
                                        }
                                        else
                                        {
                                            zjcount = zjList.Count() + 1;
                                            BomDesignDetail ZjbomDesignDetail = new BomDesignDetail
                                            {
                                                MaterialId = input[i].MaterialId,
                                                ParentMaterialId = btContent.ParentMaterialId,
                                                ParentId = guid,
                                                LevelNum = queryBomDesignDetail.LevelNum + 1,
                                                Unit1BomDosage = input[i].Unit1BomDosage,
                                                BomDesignId = queryBomDesignDetail.BomDesignId,
                                                LevelRelationship = queryBomDesignDetail.LevelRelationship + "." + zjcount,
                                                Status = (DocumentStatus)4,
                                                MaterialProperty = (int)MaterialsEnum.MaterialProperty.组件,
                                                WithinComponent = withinComponent,
                                                OrderNum = orderNum + 1
                                            };
                                            Guid returnId = Guid.Empty;
                                            returnId = await _bomDesignDetailrepository.InsertAndGetIdAsync(ZjbomDesignDetail);
                                            _unitOfWorkManager.Current.SaveChanges();
                                            var bomList = _bomDesignDetailrepository.GetAll().Where(t => t.Id == returnId).ToList();
                                            var queryBomDetailLsit = (from bomdetaillistTwo in bomList
                                                                      join materialasContent in _materialsContentrepository.GetAll() on bomdetaillistTwo.MaterialId equals materialasContent.Id
                                                                      join matialsNode in _materialsNoderepository.GetAll() on materialasContent.MaterialsNodeId equals matialsNode.Id
                                                                      join matialsNodeTwo in _materialsNoderepository.GetAll() on materialasContent.MaterialCategoryId equals matialsNodeTwo.Id
                                                           into JoinmuCate
                                                                      from muc in JoinmuCate.DefaultIfEmpty()
                                                                      join code in _sysCodeRepository.GetAll() on materialasContent.UnitId equals code.Id
                  into codeData
                                                                      from cd in codeData.DefaultIfEmpty()
                                                                      join userParentData in userData on bomdetaillistTwo.CreatorUserId equals userParentData.Id into Joinmu
                                                                      from mu in Joinmu.DefaultIfEmpty()
                                                                      select new BomDetaillist
                                                                      {
                                                                          data = new BomEditChildData
                                                                          {
                                                                              BomDesignId = bomdetaillistTwo.BomDesignId,
                                                                              MaterialId = bomdetaillistTwo.MaterialId,
                                                                              ParentMaterialId = bomdetaillistTwo.ParentMaterialId,
                                                                              Unit1BomDosage = bomdetaillistTwo.Unit1BomDosage,
                                                                              MaterialName = materialasContent.MaterialName,
                                                                              LevelRelationship = bomdetaillistTwo.LevelRelationship,
                                                                              MaterialNo = materialasContent.MaterialNo,
                                                                              Id = bomdetaillistTwo.Id,
                                                                              LevelNum = bomdetaillistTwo.LevelNum,
                                                                              MaterialTypeName = matialsNode.MaterialTypeName,
                                                                              Model = materialasContent.Model,
                                                                              Remark = materialasContent.Remark,
                                                                              MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialasContent.MaterialProperty.ToString()).ToString(),
                                                                              MaterialSegmentationName = muc == null ? "" : muc.MaterialTypeName,
                                                                              CreateUserName = mu == null ? "" : mu.Surname + mu.Name,
                                                                              Status = -1,
                                                                              CreateTime = bomdetaillistTwo.CreationTime,
                                                                              VersionNo = bomdetaillistTwo.VersionNo,
                                                                              // Btid = input.BomId,
                                                                              OrderNum = bomdetaillistTwo.OrderNum,
                                                                              UnitName = cd == null ? "" : cd.Description
                                                                          },
                                                                          children = new List<BomDetaillist>()
                                                                      }).OrderBy(t => t.data.OrderNum).ToList();
                                            //var bomDetailContent = ObjectMapper.Map<List<BomDesignDetailDto>>(bomList);
                                            if (queryBomDetailLsit.Count > 0)
                                            {
                                                resultMessage.children.AddRange(queryBomDetailLsit);
                                            }
                                        }

                                    }
                                    else
                                    {
                                        resultMessage.code = 1;
                                        resultMessage.Message = "此组件已添加,请检查";
                                        return resultMessage;
                                        //throw new UserFriendlyException("此组件已添加,请检查");
                                    }
                                }
                                else if (materalsContentResult.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件)
                                {
                                    var materalsContent = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.MaterialId == input[i].MaterialId && t.BomDesignId == queryBomDesignDetail.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件).Result;
                                    //根据芯级level 找出部套
                                    var queryBt = _bomDesignDetailrepository.GetAll().Where(t => t.LevelRelationship.StartsWith(queryBomDesignDetail.LevelRelationship) && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件 && t.BomDesignId == queryBomDesignDetail.BomDesignId);
                                    if (queryBt != null && queryBt.Count() > 0)
                                    {
                                        orderNum = queryBt.OrderByDescending(t => t.OrderNum).First().OrderNum;
                                    }
                                    if (materalsContent == null)
                                    {
                                        int k = queryBt.Count() + 1;
                                        BomDesignDetail bomDesignDetail = new BomDesignDetail
                                        {
                                            MaterialId = input[i].MaterialId,
                                            ParentMaterialId = input[i].ParentMaterialId,
                                            ParentId = guid,
                                            LevelNum = queryBomDesignDetail.LevelNum + 1,
                                            Unit1BomDosage = input[i].Unit1BomDosage,
                                            BomDesignId = queryBomDesignDetail.BomDesignId,
                                            LevelRelationship = queryBomDesignDetail.LevelRelationship + "." + k,
                                            Status = (DocumentStatus)0,
                                            MaterialProperty = (int)MaterialsEnum.MaterialProperty.部件,
                                            OrderNum = orderNum + 1
                                        };
                                        Guid returnId = Guid.Empty;
                                        returnId = await _bomDesignDetailrepository.InsertAndGetIdAsync(bomDesignDetail);
                                        _unitOfWorkManager.Current.SaveChanges();
                                        var bomList = _bomDesignDetailrepository.GetAll().Where(t => t.Id == returnId).ToList();
                                        var queryBomDetailLsit = (from bomdetaillistTwo in bomList
                                                                  join materialasContent in _materialsContentrepository.GetAll() on bomdetaillistTwo.MaterialId equals materialasContent.Id
                                                                  join matialsNode in _materialsNoderepository.GetAll() on materialasContent.MaterialsNodeId equals matialsNode.Id
                                                                  join matialsNodeTwo in _materialsNoderepository.GetAll() on materialasContent.MaterialCategoryId equals matialsNodeTwo.Id
                                                      into JoinmuCate
                                                                  from muc in JoinmuCate.DefaultIfEmpty()
                                                                  join code in _sysCodeRepository.GetAll() on materialasContent.UnitId equals code.Id
                  into codeData
                                                                  from cd in codeData.DefaultIfEmpty()
                                                                  join userParentData in userData on bomdetaillistTwo.CreatorUserId equals userParentData.Id into Joinmu
                                                                  from mu in Joinmu.DefaultIfEmpty()
                                                                  select new BomDetaillist
                                                                  {
                                                                      data = new BomEditChildData
                                                                      {
                                                                          BomDesignId = bomdetaillistTwo.BomDesignId,
                                                                          MaterialId = bomdetaillistTwo.MaterialId,
                                                                          ParentMaterialId = bomdetaillistTwo.ParentMaterialId,
                                                                          Unit1BomDosage = bomdetaillistTwo.Unit1BomDosage,
                                                                          MaterialName = materialasContent.MaterialName,
                                                                          LevelRelationship = bomdetaillistTwo.LevelRelationship,
                                                                          MaterialNo = materialasContent.MaterialNo,
                                                                          Id = bomdetaillistTwo.Id,
                                                                          LevelNum = bomdetaillistTwo.LevelNum,
                                                                          MaterialTypeName = matialsNode.MaterialTypeName,
                                                                          Model = materialasContent.Model,
                                                                          Remark = materialasContent.Remark,
                                                                          MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialasContent.MaterialProperty.ToString()).ToString(),
                                                                          MaterialSegmentationName = muc == null ? "" : muc.MaterialTypeName,
                                                                          CreateUserName = mu == null ? "" : mu.Surname + mu.Name,
                                                                          Status = -1,
                                                                          CreateTime = bomdetaillistTwo.CreationTime,
                                                                          VersionNo = bomdetaillistTwo.VersionNo,
                                                                          // Btid = input.BomId,
                                                                          OrderNum = bomdetaillistTwo.OrderNum,
                                                                          UnitName = cd == null ? "" : cd.Description
                                                                      },
                                                                      children = new List<BomDetaillist>()
                                                                  }).OrderBy(t => t.data.OrderNum).ToList();
                                        //var bomDetailContent = ObjectMapper.Map<List<BomDesignDetailDto>>(bomList);
                                        if (queryBomDetailLsit.Count > 0)
                                        {
                                            resultMessage.children.AddRange(queryBomDetailLsit);
                                        }
                                    }
                                    else
                                    {
                                        resultMessage.code = 1;
                                        resultMessage.Message = "此部件已添加,请检查";
                                        return resultMessage;
                                    }
                                }


                                //var materalsContent = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.MaterialId == input[0].MaterialId && t.BomDesignId == queryBomDesignDetail.BomDesignId).Result;

                                //if (materalsContent != null)
                                //{
                                //    throw new UserFriendlyException("部套已添加,请检查");
                                //}
                                //var queryBt = _bomDesignDetailrepository.GetAll().Where(t => t.LevelRelationship.StartsWith(queryBomDesignDetail.LevelRelationship) && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件 && t.BomDesignId == queryBomDesignDetail.BomDesignId);
                                //count = i + queryBt.Count() + 1;
                                //BomDesignDetail bomDesignDetail = new BomDesignDetail
                                //{
                                //    MaterialId = input[i].MaterialId,
                                //    ParentMaterialId = input[i].ParentMaterialId,
                                //    ParentId = guid,
                                //    LevelNum = queryBomDesignDetail.LevelNum + 1,
                                //    Unit1BomDosage = input[i].Unit1BomDosage,
                                //    BomDesignId = queryBomDesignDetail.BomDesignId,
                                //    LevelRelationship = queryBomDesignDetail.LevelRelationship + "." + count,
                                //    Status = (DocumentStatus)4,
                                //    MaterialProperty = input[i].MaterialProperty

                                //};
                                //await _bomDesignDetailrepository.InsertAsync(bomDesignDetail);
                            }

                        }
                    }
                    else
                    {
                        var materalsContentResult = _materialsContentrepository.FirstOrDefaultAsync(t => t.Id == input[0].MaterialId).Result;

                        if (materalsContentResult.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件)
                        {
                            var zjResult = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == guid).Result;
                            //找出全部零件的数量
                            var ljList = _bomDesignDetailrepository.GetAll().Where(t => t.LevelRelationship.StartsWith(zjResult.LevelRelationship) && t.BomDesignId == zjResult.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件);
                            if (ljList != null && ljList.Count() > 0)
                            {
                                orderNum = ljList.OrderByDescending(t => t.OrderNum).First().OrderNum;
                            }
                            //找出全部组件的数量
                            var zjList = _bomDesignDetailrepository.GetAll().Where(t => t.LevelRelationship.StartsWith(zjResult.LevelRelationship) && t.BomDesignId == zjResult.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件 && t.ParentId == zjResult.Id);
                            //循环找出组件下的零件数量汇总
                            int zjChildCount = 0;
                            foreach (BomDesignDetail bomDesignDetail in zjList)
                            {
                                var lj = _bomDesignDetailrepository.GetAll().Where(t => t.ParentId == bomDesignDetail.Id).Count();
                                zjChildCount += lj;
                            }
                            int ljCount = ljList.Count();
                            //全部零件数量 减去 零件汇总 +组件的数量
                            int subtractionCount = ljCount - zjChildCount + zjList.Count() + 1;

                            BomDesignDetail ZjbomDesignDetail = new BomDesignDetail
                            {
                                MaterialId = input[0].MaterialId,
                                ParentMaterialId = input[0].ParentMaterialId,
                                ParentId = guid,
                                LevelNum = queryBomDesignDetail.LevelNum + 1,
                                Unit1BomDosage = input[0].Unit1BomDosage,
                                BomDesignId = queryBomDesignDetail.BomDesignId,
                                LevelRelationship = queryBomDesignDetail.LevelRelationship + "." + subtractionCount,
                                Status = (DocumentStatus)4,
                                MaterialProperty = (int)MaterialsEnum.MaterialProperty.零件,
                                OrderNum = orderNum + 1
                            };
                            Guid returnId = Guid.Empty;
                            returnId = await _bomDesignDetailrepository.InsertAndGetIdAsync(ZjbomDesignDetail);
                            _unitOfWorkManager.Current.SaveChanges();
                            var bomList = _bomDesignDetailrepository.GetAll().Where(t => t.Id == returnId).ToList();
                            var queryBomDetailLsit = (from bomdetaillistTwo in bomList
                                                      join materialasContent in _materialsContentrepository.GetAll() on bomdetaillistTwo.MaterialId equals materialasContent.Id
                                                      join matialsNode in _materialsNoderepository.GetAll() on materialasContent.MaterialsNodeId equals matialsNode.Id
                                                      join matialsNodeTwo in _materialsNoderepository.GetAll() on materialasContent.MaterialCategoryId equals matialsNodeTwo.Id
                                                into JoinmuCate
                                                      from muc in JoinmuCate.DefaultIfEmpty()
                                                      join code in _sysCodeRepository.GetAll() on materialasContent.UnitId equals code.Id
                  into codeData
                                                      from cd in codeData.DefaultIfEmpty()
                                                      join userParentData in userData on bomdetaillistTwo.CreatorUserId equals userParentData.Id into Joinmu
                                                      from mu in Joinmu.DefaultIfEmpty()
                                                      select new BomDetaillist
                                                      {
                                                          data = new BomEditChildData
                                                          {
                                                              BomDesignId = bomdetaillistTwo.BomDesignId,
                                                              MaterialId = bomdetaillistTwo.MaterialId,
                                                              ParentMaterialId = bomdetaillistTwo.ParentMaterialId,
                                                              Unit1BomDosage = bomdetaillistTwo.Unit1BomDosage,
                                                              MaterialName = materialasContent.MaterialName,
                                                              LevelRelationship = bomdetaillistTwo.LevelRelationship,
                                                              MaterialNo = materialasContent.MaterialNo,
                                                              Id = bomdetaillistTwo.Id,
                                                              LevelNum = bomdetaillistTwo.LevelNum,
                                                              MaterialTypeName = matialsNode.MaterialTypeName,
                                                              Model = materialasContent.Model,
                                                              Remark = materialasContent.Remark,
                                                              MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialasContent.MaterialProperty.ToString()).ToString(),
                                                              MaterialSegmentationName = muc == null ? "" : muc.MaterialTypeName,
                                                              CreateUserName = mu == null ? "" : mu.Surname + mu.Name,
                                                              Status = -1,
                                                              CreateTime = bomdetaillistTwo.CreationTime,
                                                              VersionNo = bomdetaillistTwo.VersionNo,
                                                              // Btid = input.BomId,
                                                              OrderNum = bomdetaillistTwo.OrderNum,
                                                              UnitName = cd == null ? "" : cd.Description
                                                          },
                                                          children = new List<BomDetaillist>()
                                                      }).OrderBy(t => t.data.OrderNum).ToList();
                            //var bomDetailContent = ObjectMapper.Map<List<BomDesignDetailDto>>(bomList);
                            if (queryBomDetailLsit.Count > 0)
                            {
                                resultMessage.children.AddRange(queryBomDetailLsit);
                            }
                        }
                        else if (materalsContentResult.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件)
                        {
                            BomDesignDetail btContent = null;
                            int zjcount = 0;
                            var materalsContent = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.MaterialId == input[0].MaterialId && t.BomDesignId == queryBomDesignDetail.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件).Result;

                            btContent = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == queryBomDesignDetail.ParentId).Result;
                            if (materalsContent == null)
                            {
                                int withinComponent = 0;
                                // var zjParnet = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == guid).Result;
                                if (queryBomDesignDetail.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件)
                                {
                                    var zjResult = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == guid).Result;
                                    //找出全部零件的数量
                                    var ljList = _bomDesignDetailrepository.GetAll().Where(t => t.LevelRelationship.StartsWith(zjResult.LevelRelationship) && t.BomDesignId == zjResult.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件);
                                    if (ljList != null && ljList.Count() > 0)
                                    {
                                        orderNum = ljList.OrderByDescending(t => t.OrderNum).First().OrderNum;
                                    }
                                    //找出全部组件的数量
                                    var zjList = _bomDesignDetailrepository.GetAll().Where(t => t.LevelRelationship.StartsWith(zjResult.LevelRelationship) && t.BomDesignId == zjResult.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件 && t.ParentId == zjResult.Id);
                                    //循环找出组件下的零件数量汇总
                                    int zjChildCount = 0;
                                    foreach (BomDesignDetail bomDesignDetail in zjList)
                                    {
                                        var lj = _bomDesignDetailrepository.GetAll().Where(t => t.ParentId == bomDesignDetail.Id).Count();
                                        zjChildCount += lj;
                                    }
                                    int ljCount = ljList.Count();
                                    //全部零件数量 减去 零件汇总 +组件的数量
                                    int subtractionCount = ljCount - zjChildCount + zjList.Count() + 1;

                                    withinComponent = -2;
                                    BomDesignDetail ZjbomDesignDetail = new BomDesignDetail
                                    {
                                        MaterialId = input[0].MaterialId,
                                        ParentMaterialId = btContent.ParentMaterialId,
                                        ParentId = guid,
                                        LevelNum = queryBomDesignDetail.LevelNum + 1,
                                        Unit1BomDosage = input[0].Unit1BomDosage,
                                        BomDesignId = queryBomDesignDetail.BomDesignId,
                                        WithinComponent = withinComponent,
                                        LevelRelationship = queryBomDesignDetail.LevelRelationship + "." + subtractionCount,
                                        Status = (DocumentStatus)4,
                                        MaterialProperty = (int)MaterialsEnum.MaterialProperty.组件,
                                        OrderNum = orderNum + 1

                                    };
                                    Guid returnId = Guid.Empty;
                                    returnId = await _bomDesignDetailrepository.InsertAndGetIdAsync(ZjbomDesignDetail);
                                    _unitOfWorkManager.Current.SaveChanges();
                                    var bomList = _bomDesignDetailrepository.GetAll().Where(t => t.Id == returnId).ToList();
                                    var queryBomDetailLsit = (from bomdetaillistTwo in bomList
                                                              join materialasContent in _materialsContentrepository.GetAll() on bomdetaillistTwo.MaterialId equals materialasContent.Id
                                                              join matialsNode in _materialsNoderepository.GetAll() on materialasContent.MaterialsNodeId equals matialsNode.Id
                                                              join matialsNodeTwo in _materialsNoderepository.GetAll() on materialasContent.MaterialCategoryId equals matialsNodeTwo.Id
                                            into JoinmuCate
                                                              from muc in JoinmuCate.DefaultIfEmpty()
                                                              join code in _sysCodeRepository.GetAll() on materialasContent.UnitId equals code.Id
                  into codeData
                                                              from cd in codeData.DefaultIfEmpty()
                                                              join userParentData in userData on bomdetaillistTwo.CreatorUserId equals userParentData.Id into Joinmu
                                                              from mu in Joinmu.DefaultIfEmpty()
                                                              select new BomDetaillist
                                                              {
                                                                  data = new BomEditChildData
                                                                  {
                                                                      BomDesignId = bomdetaillistTwo.BomDesignId,
                                                                      MaterialId = bomdetaillistTwo.MaterialId,
                                                                      ParentMaterialId = bomdetaillistTwo.ParentMaterialId,
                                                                      Unit1BomDosage = bomdetaillistTwo.Unit1BomDosage,
                                                                      MaterialName = materialasContent.MaterialName,
                                                                      LevelRelationship = bomdetaillistTwo.LevelRelationship,
                                                                      MaterialNo = materialasContent.MaterialNo,
                                                                      Id = bomdetaillistTwo.Id,
                                                                      LevelNum = bomdetaillistTwo.LevelNum,
                                                                      MaterialTypeName = matialsNode.MaterialTypeName,
                                                                      Model = materialasContent.Model,
                                                                      Remark = materialasContent.Remark,
                                                                      MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialasContent.MaterialProperty.ToString()).ToString(),
                                                                      MaterialSegmentationName = muc == null ? "" : muc.MaterialTypeName,
                                                                      CreateUserName = mu == null ? "" : mu.Surname + mu.Name,
                                                                      Status = -1,
                                                                      CreateTime = bomdetaillistTwo.CreationTime,
                                                                      VersionNo = bomdetaillistTwo.VersionNo,
                                                                      // Btid = input.BomId,
                                                                      OrderNum = bomdetaillistTwo.OrderNum,
                                                                      UnitName = cd == null ? "" : cd.Description
                                                                  },
                                                                  children = new List<BomDetaillist>()
                                                              }).OrderBy(t => t.data.OrderNum).ToList();
                                    //var bomDetailContent = ObjectMapper.Map<List<BomDesignDetailDto>>(bomList);
                                    if (queryBomDetailLsit.Count > 0)
                                    {
                                        resultMessage.children.AddRange(queryBomDetailLsit);
                                    }
                                }
                                else
                                {

                                    //找出部套下所有组件
                                    var zjList = _bomDesignDetailrepository.GetAll().Where(t => t.LevelRelationship.StartsWith(btContent.LevelRelationship) && t.BomDesignId == queryBomDesignDetail.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件);
                                    if (zjList != null && zjList.Count() > 0)
                                    {
                                        orderNum = zjList.OrderByDescending(t => t.OrderNum).First().OrderNum;
                                    }
                                    zjcount = zjList.Count() + 1;
                                    BomDesignDetail ZjbomDesignDetail = new BomDesignDetail
                                    {
                                        MaterialId = input[0].MaterialId,
                                        ParentMaterialId = btContent.ParentMaterialId,
                                        ParentId = guid,
                                        LevelNum = queryBomDesignDetail.LevelNum + 1,
                                        Unit1BomDosage = input[0].Unit1BomDosage,
                                        BomDesignId = queryBomDesignDetail.BomDesignId,
                                        // WithinComponent = withinComponent,
                                        LevelRelationship = queryBomDesignDetail.LevelRelationship + "." + zjcount,
                                        Status = (DocumentStatus)4,
                                        MaterialProperty = (int)MaterialsEnum.MaterialProperty.组件,
                                        OrderNum = orderNum + 1

                                    };
                                    Guid returnId = Guid.Empty;
                                    returnId = await _bomDesignDetailrepository.InsertAndGetIdAsync(ZjbomDesignDetail);
                                    _unitOfWorkManager.Current.SaveChanges();
                                    var bomList = _bomDesignDetailrepository.GetAll().Where(t => t.Id == returnId).ToList();
                                    var queryBomDetailLsit = (from bomdetaillistTwo in bomList
                                                              join materialasContent in _materialsContentrepository.GetAll() on bomdetaillistTwo.MaterialId equals materialasContent.Id
                                                              join matialsNode in _materialsNoderepository.GetAll() on materialasContent.MaterialsNodeId equals matialsNode.Id
                                                              join matialsNodeTwo in _materialsNoderepository.GetAll() on materialasContent.MaterialCategoryId equals matialsNodeTwo.Id
                                       into JoinmuCate
                                                              from muc in JoinmuCate.DefaultIfEmpty()
                                                              join code in _sysCodeRepository.GetAll() on materialasContent.UnitId equals code.Id
                  into codeData
                                                              from cd in codeData.DefaultIfEmpty()
                                                              join userParentData in userData on bomdetaillistTwo.CreatorUserId equals userParentData.Id into Joinmu
                                                              from mu in Joinmu.DefaultIfEmpty()
                                                              select new BomDetaillist
                                                              {
                                                                  data = new BomEditChildData
                                                                  {
                                                                      BomDesignId = bomdetaillistTwo.BomDesignId,
                                                                      MaterialId = bomdetaillistTwo.MaterialId,
                                                                      ParentMaterialId = bomdetaillistTwo.ParentMaterialId,
                                                                      Unit1BomDosage = bomdetaillistTwo.Unit1BomDosage,
                                                                      MaterialName = materialasContent.MaterialName,
                                                                      LevelRelationship = bomdetaillistTwo.LevelRelationship,
                                                                      MaterialNo = materialasContent.MaterialNo,
                                                                      Id = bomdetaillistTwo.Id,
                                                                      LevelNum = bomdetaillistTwo.LevelNum,
                                                                      MaterialTypeName = matialsNode.MaterialTypeName,
                                                                      Model = materialasContent.Model,
                                                                      Remark = materialasContent.Remark,
                                                                      MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialasContent.MaterialProperty.ToString()).ToString(),
                                                                      MaterialSegmentationName = muc == null ? "" : muc.MaterialTypeName,
                                                                      CreateUserName = mu==null?"":mu.Surname + mu.Name,
                                                                      Status = -1,
                                                                      CreateTime = bomdetaillistTwo.CreationTime,
                                                                      VersionNo = bomdetaillistTwo.VersionNo,
                                                                      // Btid = input.BomId,
                                                                      OrderNum = bomdetaillistTwo.OrderNum,
                                                                      UnitName = cd == null ? "" : cd.Description
                                                                  },
                                                                  children = new List<BomDetaillist>()
                                                              }).OrderBy(t => t.data.OrderNum).ToList();
                                    //var bomDetailContent = ObjectMapper.Map<List<BomDesignDetailDto>>(bomList);
                                    if (queryBomDetailLsit.Count > 0)
                                    {
                                        resultMessage.children.AddRange(queryBomDetailLsit);
                                    }
                                }

                            }
                            else
                            {
                                resultMessage.code = 1;
                                resultMessage.Message = "此组件已添加,请检查";
                                return resultMessage;
                                //throw new UserFriendlyException("此组件已添加,请检查");
                            }
                        }
                        else if (materalsContentResult.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件)
                        {
                            var materalsContent = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.MaterialId == input[0].MaterialId && t.BomDesignId == queryBomDesignDetail.BomDesignId && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件).Result;
                            //根据芯级level 找出部套
                            var queryBt = _bomDesignDetailrepository.GetAll().Where(t => t.LevelRelationship.StartsWith(queryBomDesignDetail.LevelRelationship) && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件 && t.BomDesignId == queryBomDesignDetail.BomDesignId);
                            if (queryBt != null && queryBt.Count() > 0)
                            {
                                orderNum = queryBt.OrderByDescending(t => t.OrderNum).First().OrderNum;
                            }
                            if (materalsContent == null)
                            {
                                int i = queryBt.Count() + 1;
                                BomDesignDetail bomDesignDetail = new BomDesignDetail
                                {
                                    MaterialId = input[0].MaterialId,
                                    ParentMaterialId = input[0].ParentMaterialId,
                                    ParentId = guid,
                                    LevelNum = queryBomDesignDetail.LevelNum + 1,
                                    Unit1BomDosage = input[0].Unit1BomDosage,
                                    BomDesignId = queryBomDesignDetail.BomDesignId,
                                    LevelRelationship = queryBomDesignDetail.LevelRelationship + "." + i,
                                    Status = (DocumentStatus)4,
                                    MaterialProperty = (int)MaterialsEnum.MaterialProperty.部件,
                                    OrderNum = orderNum + 1
                                };
                                Guid returnId = Guid.Empty;
                                returnId = await _bomDesignDetailrepository.InsertAndGetIdAsync(bomDesignDetail);
                                _unitOfWorkManager.Current.SaveChanges();
                                var bomList = _bomDesignDetailrepository.GetAll().Where(t => t.Id == returnId).ToList();
                                var queryBomDetailLsit = (from bomdetaillistTwo in bomList
                                                          join materialasContent in _materialsContentrepository.GetAll() on bomdetaillistTwo.MaterialId equals materialasContent.Id
                                                          join matialsNode in _materialsNoderepository.GetAll() on materialasContent.MaterialsNodeId equals matialsNode.Id
                                                          join matialsNodeTwo in _materialsNoderepository.GetAll() on materialasContent.MaterialCategoryId equals matialsNodeTwo.Id
                                  into JoinmuCate
                                                          from muc in JoinmuCate.DefaultIfEmpty()
                                                          join code in _sysCodeRepository.GetAll() on materialasContent.UnitId equals code.Id
                  into codeData
                                                          from cd in codeData.DefaultIfEmpty()
                                                          join userParentData in userData on bomdetaillistTwo.CreatorUserId equals userParentData.Id into Joinmu
                                                          from mu in Joinmu.DefaultIfEmpty()
                                                          select new BomDetaillist
                                                          {
                                                              data = new BomEditChildData
                                                              {
                                                                  BomDesignId = bomdetaillistTwo.BomDesignId,
                                                                  MaterialId = bomdetaillistTwo.MaterialId,
                                                                  ParentMaterialId = bomdetaillistTwo.ParentMaterialId,
                                                                  Unit1BomDosage = bomdetaillistTwo.Unit1BomDosage,
                                                                  MaterialName = materialasContent.MaterialName,
                                                                  LevelRelationship = bomdetaillistTwo.LevelRelationship,
                                                                  MaterialNo = materialasContent.MaterialNo,
                                                                  Id = bomdetaillistTwo.Id,
                                                                  LevelNum = bomdetaillistTwo.LevelNum,
                                                                  MaterialTypeName = matialsNode.MaterialTypeName,
                                                                  Model = materialasContent.Model,
                                                                  Remark = materialasContent.Remark,
                                                                  MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialasContent.MaterialProperty.ToString()).ToString(),
                                                                  MaterialSegmentationName = muc == null ? "" : muc.MaterialTypeName,
                                                                  CreateUserName = mu == null ? "" : mu.Surname + mu.Name,
                                                                  Status = -1,
                                                                  CreateTime = bomdetaillistTwo.CreationTime,
                                                                  VersionNo = bomdetaillistTwo.VersionNo,
                                                                  // Btid = input.BomId,
                                                                  OrderNum = bomdetaillistTwo.OrderNum,
                                                                  UnitName = cd == null ? "" : cd.Description
                                                              },
                                                              children = new List<BomDetaillist>()
                                                          }).OrderBy(t => t.data.OrderNum).ToList();
                                //var bomDetailContent = ObjectMapper.Map<List<BomDesignDetailDto>>(bomList);
                                if (queryBomDetailLsit.Count > 0)
                                {
                                    resultMessage.children.AddRange(queryBomDetailLsit);
                                }
                            }
                            else
                            {
                                resultMessage.code = 1;
                                resultMessage.Message = "此部件已添加,请检查";
                                return resultMessage;
                            }
                        }
                    }
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// Bom维护头部新增子级按钮
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<BomDetaillist> CreateChildrenTopNode(List<BomDesignDetailDto> input, Guid guid)
        {
            var userData = _userRepository.GetAll().ToList();
            BomDetaillist resultMessage = new BomDetaillist();
            resultMessage.children = new List<BomDetaillist>();
            try
            {
                if (input != null)
                {
                    //var queryBomDesignDetail = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.BomDesignId == guid).Result;
                    //if (queryBomDesignDetail != null)
                    //{
                    //    int count = 0;
                    //    foreach (BomDesignDetailDto bdd in input)
                    //    {
                    //        var queryBomDesignDetailCount = _bomDesignDetailrepository.Count(t => t.BomDesignId == guid&&t.ParentId ==Guid.Empty);
                    //        count = queryBomDesignDetailCount+1;
                    //        BomDesignDetail bomDesignDetail = new BomDesignDetail
                    //        {
                    //            MaterialId = bdd.MaterialId,
                    //            ParentMaterialId = bdd.MaterialId,
                    //            ParentId = Guid.Empty,
                    //            LevelNum = 2,
                    //            // Unit1BomDosage =bdd.Unit1BomDosage,
                    //            BomDesignId = guid,
                    //            LevelRelationship = 1 + "." + count,
                    //            MaterialProperty = bdd.MaterialProperty
                    //        };
                    //        await _bomDesignDetailrepository.InsertAsync(bomDesignDetail);
                    //    }
                    //}
                    //var queryBomDesignDetail = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.BomDesignId == guid).Result;
                    //if (queryBomDesignDetail != null)
                    //{
                    int count = 0;
                    foreach (BomDesignDetailDto bdd in input)
                    {
                        var xjResult = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.MaterialId == bdd.MaterialId && t.BomDesignId == guid).Result;

                        if (xjResult != null)
                        {
                            var queryMaterilsContent = _materialsContentrepository.FirstOrDefaultAsync(t => t.Id == bdd.MaterialId).Result;
                            resultMessage.Message = "此芯级已添加：" + queryMaterilsContent.MaterialName;
                            resultMessage.code = 1;
                            return resultMessage;
                        }
                        var queryBomDesignDetailCount = _bomDesignDetailrepository.Count(t => t.BomDesignId == guid && t.ParentId == Guid.Empty);
                        count = queryBomDesignDetailCount + 1;
                        BomDesignDetail bomDesignDetail = new BomDesignDetail
                        {
                            MaterialId = bdd.MaterialId,
                            ParentMaterialId = bdd.MaterialId,
                            ParentId = Guid.Empty,
                            LevelNum = 2,
                            // Unit1BomDosage =bdd.Unit1BomDosage,
                            BomDesignId = guid,
                            LevelRelationship = 1 + "." + count,
                            MaterialProperty = bdd.MaterialProperty,
                            OrderNum = count

                        };
                        Guid returnId = Guid.Empty;
                         returnId =await  _bomDesignDetailrepository.InsertAndGetIdAsync(bomDesignDetail);
                        _unitOfWorkManager.Current.SaveChanges();
                        var bomList = _bomDesignDetailrepository.GetAll().Where(t => t.Id == returnId).ToList();
                      var queryBomDetailLsit =  (from bomdetaillistTwo in bomList
                         join materialasContent in _materialsContentrepository.GetAll() on bomdetaillistTwo.MaterialId equals materialasContent.Id
                         join matialsNode in _materialsNoderepository.GetAll() on materialasContent.MaterialsNodeId equals matialsNode.Id
                         join userParentData in userData on bomdetaillistTwo.CreatorUserId equals userParentData.Id into Joinmu
                         from mu in Joinmu.DefaultIfEmpty()
                         select new BomDetaillist
                         {
                             data = new BomEditChildData
                             {
                                 BomDesignId = bomdetaillistTwo.BomDesignId,
                                 MaterialId = bomdetaillistTwo.MaterialId,
                                 ParentMaterialId = bomdetaillistTwo.ParentMaterialId,
                                 Unit1BomDosage = bomdetaillistTwo.Unit1BomDosage,
                                 MaterialName = materialasContent.MaterialName,
                                 LevelRelationship = bomdetaillistTwo.LevelRelationship,
                                 MaterialNo = materialasContent.MaterialNo,
                                 Id = bomdetaillistTwo.Id,
                                 LevelNum = bomdetaillistTwo.LevelNum,
                                 MaterialTypeName = matialsNode.MaterialTypeName,
                                 Model = materialasContent.Model,
                                 Remark = materialasContent.Remark,
                                 MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialasContent.MaterialProperty.ToString()).ToString(),
                                 CreateUserName = mu.Surname + mu.Name,
                                 Status = -1,
                                 CreateTime = bomdetaillistTwo.CreationTime,
                                 VersionNo = bomdetaillistTwo.VersionNo,
                                // Btid = input.BomId,
                                 OrderNum = bomdetaillistTwo.OrderNum
                             },
                             children = new List<BomDetaillist>()
                         }).OrderBy(t => t.data.OrderNum).ToList();
                        //var bomDetailContent = ObjectMapper.Map<List<BomDesignDetailDto>>(bomList);
                        if (queryBomDetailLsit.Count > 0) 
                        {
                            resultMessage.children.AddRange(queryBomDetailLsit);
                        }
                    }
                    //  }
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 更新bom
        /// </summary>
        /// <param name="bomDetaillist"></param>
        /// <returns></returns>
        public async Task UpdateBomList(BomDetaillist bomDetaillist)
        {
            //要点：入参从第三级包含第三级开始
            Guid id = Guid.Empty;
            Guid parentId = Guid.Empty;
            int LevelNum = 0;
            //得到最外层的id 和 parentid
            //id:根据id删除bom明细
            //parentid：获取外层的id  如果前端不传 则用id获取
            //根据parentid 获取level  用于层级计算
            if (bomDetaillist != null)
            {
                id = bomDetaillist.data.Id;
                //这里如果前端不传可以用id查出
                parentId = bomDetaillist.data.ParentId;
                //根据id 全部删除
                //  await _bomDesignDetailrepository.DeleteAsync(t => t.ParentId == id);
                //根据id 获取外层层级
                var queryOutsideData = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == parentId).Result;
                if (queryOutsideData != null)
                {
                    LevelNum = queryOutsideData.LevelNum;
                    BomGuid = queryOutsideData.BomDesignId;
                }
                #region 添加用户权限
                if (queryOutsideData.CreatorUserId != GetCurrentUser().Id) //add 11/30
                {
                    throw new UserFriendlyException("非本人创建，没有修改该数据的权限！");
                }
                #endregion
            }
            //循环插入
            //(1)：根据 MaterialProperty 判断 是否是部套 取出id
            if (bomDetaillist.data.Attribute == (int)MaterialsEnum.MaterialProperty.组件)
            {
                id = bomDetaillist.data.Id;
                LevelNum = bomDetaillist.data.LevelNum;
            }
            #region 递归循环child 
            foreach (BomDetaillist bomdetail in bomDetaillist.children)
            {
                AddChilden(bomdetail, LevelNum, id);
            }
            if (bomDesignDetails.Count() > 0)
            {
                foreach (BomDesignDetail bomDesignDetail in bomDesignDetails)
                {
                    var queryBomDetailList = _bomDesignDetailrepository.GetAll().Where(t => t.Id == bomDesignDetail.Id);
                    if (queryBomDetailList.Count() > 0)
                    {
                        await _bomDesignDetailrepository.UpdateAsync(bomDesignDetail);
                    }
                    else
                    {
                        await _bomDesignDetailrepository.InsertAsync(bomDesignDetail);//更具业务需求扩展，暂时不用，如果后期更新bom同时增加子级会用到 
                    }
                }
            }
            #endregion
        }

        /// <summary>
        /// 保存送审
        /// </summary>
        public void PushMoadifManage(BomApprovalDto input)
        {
            //if (input.CreateFlag == 0)
            //{
            //var tempModif = _bomDesignDetailrepository.GetAll().Where(d => d.Id == input.BomId && (d.Status == DocumentStatus.编制中 || d.Status == DocumentStatus.审核中)).FirstOrDefault();
            //if (tempModif != null)
            //{
            //    throw new UserFriendlyException("存有发起变更同一个设计bom变更业务");
            //}
            //PushBusInput push = new PushBusInput();
            //push.WorkAuditorList = input.WorkAuditorList;
            //push.Type = input.Type; //发起审核默认  变更工艺规程流程为0
            //push.FunModule = "变更管理";
            //push.Menu = "设计bom变更管理";
            //Guid busId = _workFlowAppService.PushBusinessApplication(push);

            //var bomDesignDetailContent = _bomDesignDetailrepository.FirstOrDefaultAsync(t=>t.Id ==input.BomId).Result;
            //if (bomDesignDetailContent != null) 
            //{
            //    bomDesignDetailContent.ModifiChangeId = busId;
            //    bomDesignDetailContent.Status = DocumentStatus.审核中;
            //    _bomDesignDetailrepository.UpdateAsync(bomDesignDetailContent);
            //}
        }
        /// <summary>
        /// 根据业务Id查询变更管理业务详情
        /// </summary>
        /// <param name="bappId"></param>
        /// <returns></returns>
        public BomModifResult DisplayBomBusinessById(Guid bappId)
        {
            BomModifResult result = new BomModifResult();
            var bomDesignContent = _bomDesignDetailrepository.FirstOrDefault(d => d.ModifiChangeId == bappId && d.MaterialProperty == (int)MaterialsEnum.MaterialProperty.部件);
            if (bomDesignContent != null)
            {
                var business = _businessApplicationRepository.Get(bappId);
                var workNode = _workFlowNodeRepository.GetAll().First(d => d.WnID == business.BAppType && d.WfID == business.Status);
                var workAuditorList = _workAuditorRepository.GetAll().Where(d => d.BappId == bappId);

                var currentUser = GetCurrentUser();
                var currentRoles = _userRoleRepository.GetAll().Where(userRole => userRole.UserId == currentUser.Id).Select(userRole => userRole.RoleId).ToArray();
                if (workNode.NextNode == "0")
                {//业务结束只能查看
                    result.DisplayApproval = false;
                }
                else if ((currentUser.Id == business.ExamineUserId)/*|| (currentUser.Roles.Select(d => d.RoleId).Contains(Convert.ToInt32(workNode.Handlers)) && currentUser.Id != business.UserID)*/)
                {//处理用户业务的节点
                    result.DisplayApproval = true;
                }
                else if (currentRoles.Length > 0)
                {
                    string[] bigArr = Array.ConvertAll(currentRoles, _ => _.ToString());
                    if (workNode.Handlers != null)
                    {
                        var smallArr = workNode.Handlers.Split(',').ToArray();
                        var exceptArr = bigArr.Intersect(smallArr);
                        if (exceptArr.Any())
                        {
                            if (business.ExamineUserId == null)
                            {
                                result.DisplayApproval = true;
                            }
                        }
                    }


                }
                else
                {//非本人处理，只是查看
                    result.DisplayApproval = false;
                }
                var users = _userRepository.GetAll().ToList();
                BomDetaillist bomDetaillist = new BomDetaillist();
                GetBomNodeTreeListInput getBomNodeTreeListInput = new GetBomNodeTreeListInput();

                getBomNodeTreeListInput.BomId = bomDesignContent.Id;
                bomDetaillist = GetBomChildTreeGrid(getBomNodeTreeListInput);
                result.BomDetaillists = bomDetaillist;
                result.WorkAuditorList = (from tempQy in workAuditorList
                                          join wf in _workFlowNodeRepository.GetAll() on tempQy.WfID equals wf.WfID
                                          join user in users on tempQy.UserId equals user.Id
                                          where wf.WnID == tempQy.WnID
                                          select new WorkAuditorOutput
                                          {
                                              BappId = tempQy.BappId,
                                              WfName = wf.WnName,
                                              UserName = user.Surname + user.Name,
                                              Result = tempQy.Result,
                                              Remark = tempQy.Remark,
                                              AuditTime = tempQy.AuditTime
                                          }).ToList();
            }
            return result;
        }
        /// <summary>
        /// 审批变更管理
        /// </summary>
        /// <param name="input"></param>
        public void ApprovebomModif(ApproveInput input)
        {
            int status = 0;
            _workFlowAppService.SendToFlow(input.BappId, input.Operation, input.Remark, out status);
            List<BomDesignDetail> bomDesignDetailList = new List<BomDesignDetail>();
            if (status == 99)
            {
                var bomdesign = _bomDesignDetailrepository.GetAll().Where(d => d.ModifiChangeId == input.BappId);
                if (bomdesign != null && bomdesign.Count() > 0)
                {
                    foreach (BomDesignDetail bomDesignDetail in bomdesign)
                    {
                        bomDesignDetail.Status = DocumentStatus.已发布;
                        bomDesignDetailList.Add(bomDesignDetail);
                    }
                    _bomDesignDetailrepository.GetDbContext().BulkUpdate(bomDesignDetailList);
                }
            }
            if (status == 100)
            {
                var bomdesign = _bomDesignDetailrepository.GetAll().Where(d => d.ModifiChangeId == input.BappId);
                if (bomdesign != null && bomdesign.Count() > 0)
                {
                    foreach (BomDesignDetail bomDesignDetail in bomdesign)
                    {
                        bomDesignDetail.Status = DocumentStatus.被驳回;
                        bomDesignDetailList.Add(bomDesignDetail);
                    }
                    _bomDesignDetailrepository.GetDbContext().BulkUpdate(bomDesignDetailList);
                }
            }
        }
        /// <summary>
        /// 送审
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public async Task<ResultMessage> SendAudit(BomApprovalDto input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                //if (input.CreateFlag == 0)
                //{d.Status == DocumentStatus.编制中 ||

                var tempModif = _bomDesignDetailrepository.GetAll().Where(d => d.Id == input.BomId && (d.Status == DocumentStatus.审核中)).FirstOrDefault();
                if (tempModif != null)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "存有发起变更同一个设计bom变更业务";
                    return resultMessage;
                    //throw new UserFriendlyException("存有发起变更同一个设计bom变更业务");
                }
                var bomDesignDetailContent = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == input.BomId).Result;
                if (bomDesignDetailContent.CreatorUserId != GetCurrentUser().Id) //add 11/30
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "非本人创建，不能送审！";
                    return resultMessage;
                    //throw new UserFriendlyException("非本人创建，不能送审！");
                }
                if (bomDesignDetailContent.Status == DocumentStatus.被驳回)
                {
                    RejectPushBusInput reject = new RejectPushBusInput();
                    reject.WorkAuditorList = input.WorkAuditorList;
                    reject.Type = input.Type;
                    reject.Id = bomDesignDetailContent.ModifiChangeId;
                    _workFlowAppService.RejectPushBusinessApplication(reject);
                    SendAuditUpdateStatus(bomDesignDetailContent);
                }
                else
                {

                    PushBusInput push = new PushBusInput();
                    push.WorkAuditorList = input.WorkAuditorList;
                    push.Type = input.Type;
                    push.FunModule = "变更管理";
                    push.Menu = "设计bom变更管理";
                    //add 12/1 start
                    var businessNumber = _codeFormatDescAppServiceRepository.GetCodeFormat("设计BOM送审");
                    if (businessNumber == null)
                    {
                        businessNumber = _codeFormatDescAppServiceRepository.GetOrderCode("BGGL", "yyyyMMdd", 1, 5, 1);
                    }
                    push.BusinessNumber = businessNumber;
                    //add 12/1 end
                    //查出部套
                    var queryBomDesignBtContent = (from bomBt in _bomDesignDetailrepository.GetAll().Where(t => t.Id == input.BomId)
                                                   join materialsData in _materialsContentrepository.GetAll() on bomBt.MaterialId equals materialsData.Id
                                                   select new
                                                   {
                                                       btName = materialsData.MaterialName,
                                                       xjId = bomBt.ParentId,
                                                       bomDesignId = bomBt.BomDesignId
                                                   }).FirstOrDefaultAsync().Result;
                    if (queryBomDesignBtContent != null)
                    {
                        var queryBomXjContent = (from bomXjName in _bomDesignDetailrepository.GetAll().Where(t => t.Id == queryBomDesignBtContent.xjId)
                                                 join materialsData in _materialsContentrepository.GetAll() on bomXjName.MaterialId equals materialsData.Id
                                                 select new
                                                 {
                                                     xjName = materialsData.MaterialName
                                                 }).FirstOrDefaultAsync().Result;
                        var queryBomXhFcContent = (from bomXhFc in _bomDesignrepository.GetAll().Where(t => t.Id == queryBomDesignBtContent.bomDesignId)
                                                   select new { module = bomXhFc.Module, sendTime = bomXhFc.SendTime }
                                                  ).FirstOrDefaultAsync().Result;
                        push.BusinessDesc = "型号：" + queryBomXhFcContent.module + "发次：" + queryBomXhFcContent.sendTime + "芯级：" + queryBomXjContent.xjName + "部套：" + queryBomDesignBtContent.btName;
                    }
                    Guid busId = _workFlowAppService.PushBusinessApplication(push);
                    if (bomDesignDetailContent != null)
                    {
                        //更新主表
                        bomDesignDetailContent.ModifiChangeId = busId;
                        bomDesignDetailContent.Status = DocumentStatus.审核中;
                        SendAuditUpdateStatus(bomDesignDetailContent);
                    }
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 更新bom用
        /// </summary>
        /// <param name="bomdetail"></param>
        /// <param name="levelNum"></param>
        /// <param name="parentId"></param>
        private void AddChilden(BomDetaillist bomdetail, int levelNum, Guid parentId)
        {
            Guid bomdesignId = Guid.Empty;
            if (bomdetail.data != null)
            {
                BomDesignDetail bomDesignDetail = new BomDesignDetail
                {
                    Id = bomdetail.data.Id == null ? Guid.NewGuid() : bomdetail.data.Id,//写法为后期扩展用
                    BomDesignId = BomGuid,
                    MaterialId = bomdetail.data.MaterialId,
                    ParentId = parentId,
                    ParentMaterialId = parentId,
                    Unit1BomDosage = bomdetail.data.Unit1BomDosage,
                    LevelNum = levelNum + 1,
                    Status = 0
                };
                bomdesignId = bomDesignDetail.Id;//写法为后期扩展用
                bomDesignDetails.Add(bomDesignDetail);
            }
            else
            {
                return;
            }
            //如果children有数据
            if (bomdetail.children.Count() > 0)
            {
                for (int i = bomdetail.children.ToList().Count - 1; i >= 0; i--)
                {

                    AddChilden(bomdetail.children[i], levelNum + 1, bomdesignId);
                }
            }
        }
        /// <summary>
        ///  Bom维护整树查看
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public List<BomEditList> GetBomTreeGrid(GetBomNodeTreeListInput input)
        {
            var userData = _userRepository.GetAll().ToList();
            var queryBomDetailList = _bomDesignDetailrepository.GetAll().ToList();
            var queryBomDesignList = _bomDesignrepository.GetAll().ToList();
            Guid guid = Guid.NewGuid();
            List<BomEditList> querybomEditList = null;
            List<BomDetaillist> querybomdetaillists = null;
            List<BomDetaillist> bomdetailList = new List<BomDetaillist>();
            BomDetaillist bomdetaillist = new BomDetaillist();
            bomdetailList.Clear();
            //根据传入父节点id 查出bom主表的相关信息 *****IQueryable 会记录上一次请求的数据 在此记录************** 2021-07-05 曲冰
            //  var bomConent = _bomDesignrepository.GetAllIncluding(t => t.BomDesignDetails).Where(d => d.Id == input.BomId).ToList();

            //var bomConent1 = from bomDesign in _bomDesignrepository.GetAllIncluding(t => t.BomDesignDetails).Where(d => d.Id == input.BomId)
            //                 join materialasContent in _materialsContentrepository.GetAll() on
            //                     bomDesign.MaterialsContentId equals materialasContent.Id
            //                 select new BomEditList
            //                 {
            //                     MaterialsContentId = bomDesign.MaterialsContentId,
            //                     BomType = bomDesign.BomType,
            //                     VersionNo = bomDesign.VersionNo,
            //                     IsUsed = bomDesign.IsUsed,
            //                     ChangeId = bomDesign.ChangeId,
            //                     Status = bomDesign.Status,
            //                     MaterialName = materialasContent.MaterialName,
            //                     MaterialNo = materialasContent.MaterialNo,
            //                     Id = materialasContent.Id,
            //                     bomDetailList = bomDesign.BomDesignDetails
            //                 };
            var queryBomDesigns = _bomDesignrepository.GetAll().Where(t => t.Id == input.BomId);
            if (queryBomDesigns.Count() > 0)
            {
                querybomEditList = (from bomDesign in queryBomDesignList.Where(t => t.Id == input.BomId)
                                    join materialasContent in _materialsContentrepository.GetAll() on
                                    bomDesign.MaterialsContentId equals materialasContent.Id
                                    join matialsNode in _materialsNoderepository.GetAll() on materialasContent.MaterialsNodeId equals matialsNode.Id
                                    join userParentData in userData on bomDesign.CreatorUserId equals userParentData.Id into Joinmu
                                    from mu in Joinmu.DefaultIfEmpty()
                                    select new BomEditList
                                    {
                                        data = new BomEditParentData
                                        {
                                            MaterialsContentId = bomDesign.MaterialsContentId,
                                            BomType = bomDesign.BomType,
                                            VersionNo = bomDesign.VersionNo,
                                            IsUsed = bomDesign.IsUsed,
                                            ChangeId = bomDesign.ChangeId,
                                            Status = 0,
                                            MaterialName = materialasContent.MaterialName,
                                            MaterialNo = materialasContent.MaterialNo,
                                            Id = materialasContent.Id,
                                            MaterialTypeName = matialsNode.MaterialTypeName,
                                            Model = materialasContent.Model,
                                            MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialasContent.MaterialProperty.ToString()).ToString(),
                                            Remark = materialasContent.Remark,
                                            CreateUserName = mu.Surname + mu.Name,
                                            CreateTime = bomDesign.CreationTime,
                                            Btid = input.BomId

                                        }
                                    }).OrderBy(t => t.data.OrderNum).ToList();
            }
            //根据bom父节点id找出相关二级节点信息
            querybomdetaillists = (from bomdetaillistTwo in queryBomDetailList.Where(t => t.BomDesignId == input.BomId && t.ParentId == Guid.Empty)
                                   join materialasContent in _materialsContentrepository.GetAll() on bomdetaillistTwo.MaterialId equals materialasContent.Id
                                   join matialsNode in _materialsNoderepository.GetAll() on materialasContent.MaterialsNodeId equals matialsNode.Id
                                   join userParentData in userData on bomdetaillistTwo.CreatorUserId equals userParentData.Id into Joinmu
                                   from mu in Joinmu.DefaultIfEmpty()
                                   select new BomDetaillist
                                   {
                                       data = new BomEditChildData
                                       {
                                           BomDesignId = bomdetaillistTwo.BomDesignId,
                                           MaterialId = bomdetaillistTwo.MaterialId,
                                           ParentMaterialId = bomdetaillistTwo.ParentMaterialId,
                                           Unit1BomDosage = bomdetaillistTwo.Unit1BomDosage,
                                           MaterialName = materialasContent.MaterialName,
                                           LevelRelationship = bomdetaillistTwo.LevelRelationship,
                                           MaterialNo = materialasContent.MaterialNo,
                                           Id = bomdetaillistTwo.Id,
                                           LevelNum = bomdetaillistTwo.LevelNum,
                                           MaterialTypeName = matialsNode.MaterialTypeName,
                                           Model = materialasContent.Model,
                                           Remark = materialasContent.Remark,
                                           MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialasContent.MaterialProperty.ToString()).ToString(),
                                           CreateUserName = mu.Surname + mu.Name,
                                           Status = 0,
                                           CreateTime = bomdetaillistTwo.CreationTime,
                                           VersionNo = bomdetaillistTwo.VersionNo,
                                           Btid = input.BomId,
                                           OrderNum = bomdetaillistTwo.OrderNum
                                       },
                                       children = new List<BomDetaillist>()
                                   }).OrderBy(t => t.data.OrderNum).ToList();
            if (querybomdetaillists != null && querybomdetaillists.Count > 0)
            {
                foreach (BomDetaillist bomdetaillists in querybomdetaillists)
                {
                    querybomEditList.ToList()[0].children.Add(bomdetaillists);
                    //GetBomLookList(querybomEditList.ToList()[0], bomdetaillists.Id, bomdetaillists);
                    guid = bomdetaillists.data.Id;
                    bomdetaillist = bomdetaillists;
                    GetBomLookList(guid, bomdetaillist, userData, Guid.Empty, queryBomDetailList);
                    bomdetailList.Add(bomdetaillist);
                }
                querybomEditList.ToList()[0].children = bomdetailList;
            }

            // querybomEditListStatic = querybomEditList;
            if (querybomEditList != null)
            {
                return querybomEditList.ToList();
            }
            return new List<BomEditList>();
        }

        private BomDetaillist GetBomLookList(Guid id, BomDetaillist bomdetaillist, List<User> users, Guid BTid,List<BomDesignDetail> bomDesignDetail)
        {
            var bomChildBomDetailCount = _bomDesignDetailrepository.Count(t => t.ParentId == id);
            if (bomChildBomDetailCount > 0)
            {
                //var ddd = (from cc in _bomDesignDetailrepository.GetAll() select cc).OrderBy(t => t.CreationTime);

                //var bomChildBomDetailListData = (from cc in _bomDesignDetailrepository.GetAll() //.Where(t => t.ParentId == id).OrderBy<BomDesignDetail,int>(t=>t.OrderNum);
                //                                 select new
                //                                 {
                //                                     CreatorUserId=cc.CreatorUserId,
                //                                     MaterialId = cc.MaterialId,
                //                                     OrderNum = cc.OrderNum
                //                                 }).OrderBy(d => d.OrderNum);

                var queryChildBomdetaillist = (from bomChildBomDetailList in bomDesignDetail.Where(t => t.ParentId == id)
                                              join materialasContent in _materialsContentrepository.GetAll() on bomChildBomDetailList.MaterialId equals materialasContent.Id
                                              join matialsNode in _materialsNoderepository.GetAll() on materialasContent.MaterialsNodeId equals matialsNode.Id
                                              join matialsNodeChild in _materialsNoderepository.GetAll() on materialasContent.MaterialCategoryId equals matialsNodeChild.Id into mtnc
                                              from mt in mtnc.DefaultIfEmpty()
                                              join code in _sysCodeRepository.GetAll() on materialasContent.UnitId equals code.Id
                                   into codeData
                                              from cd in codeData.DefaultIfEmpty()
                                              join userData in users on bomChildBomDetailList.CreatorUserId equals userData.Id into Joinmu
                                              from mu in Joinmu.DefaultIfEmpty()
                                              select new BomDetaillist
                                              {
                                                  data = new BomEditChildData
                                                  {
                                                      BomDesignId = bomChildBomDetailList.BomDesignId,
                                                      MaterialId = bomChildBomDetailList.MaterialId,
                                                      ParentMaterialId = bomChildBomDetailList.ParentMaterialId,
                                                      Unit1BomDosage = bomChildBomDetailList.Unit1BomDosage,
                                                      MaterialName = materialasContent.MaterialName,
                                                      LevelRelationship = bomChildBomDetailList.LevelRelationship,
                                                      Id = bomChildBomDetailList.Id,
                                                      ParentId = bomChildBomDetailList.ParentId, 
                                                      LevelNum = bomChildBomDetailList.LevelNum,
                                                      Model = materialasContent.Model,
                                                      UnitName = cd ==null?"": cd.Code,
                                                      IsKeyPart = Enum.Parse(typeof(MaterialsEnum.IsKeyPart), materialasContent.IsKeyPart.ToString()).ToString(),
                                                      Remark = materialasContent.Remark,
                                                      MaterialTypeName = matialsNode.MaterialTypeName,
                                                      MaterialSegmentationName = mt==null?"":mt.MaterialTypeName,
                                                      MaterialNo = materialasContent.MaterialNo,
                                                      MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialasContent.MaterialProperty.ToString()).ToString(),
                                                      Status = (int)bomChildBomDetailList.Status,
                                                      CreateUserName = mu.Surname + mu.Name,
                                                      DeleStatus = (int)bomChildBomDetailList.Status == (int)DocumentStatus.已发布 || (int)bomChildBomDetailList.Status == (int)DocumentStatus.审核中 ? -1 : 0,
                                                      CreateTime = bomChildBomDetailList.CreationTime,
                                                      VersionNo = bomChildBomDetailList.VersionNo,
                                                      Btid = BTid,
                                                      OrderNum = bomChildBomDetailList.OrderNum,
                                                      YearsNo = bomChildBomDetailList.YearsNo,
                                                      WithinComponent = bomChildBomDetailList.WithinComponent
                                                  },
                                                  children = new List<BomDetaillist>()
                                              }).OrderBy(t => t.data.OrderNum).ToList();
                if (queryChildBomdetaillist != null && queryChildBomdetaillist.Count() > 0)
                {
                    bomdetaillist.children = new List<BomDetaillist>();
                    bomdetaillist.children.AddRange(queryChildBomdetaillist);

                    for (int i = queryChildBomdetaillist.ToList().Count - 1; i >= 0; i--)
                    {
                        if (queryChildBomdetaillist.ToList()[i].data.ParentId == bomdetaillist.data.Id)
                        {
                            //if (isbool == false)
                            //{
                            //    if (queryChildBomdetaillist.ToList()[i].data.Status == (int)DocumentStatus.已发布 || queryChildBomdetaillist.ToList()[i].data.Status == (int)DocumentStatus.审核中)
                            //    {
                            //        isbool = true;
                            //    }
                            //}
                            //if(isbool ==true)
                            //{
                            //    bomdetaillist.children[i].data.Status = 3;+
                            //}
                            //TimeSpan timeSpan = queryChildBomdetaillist.ToList()[i].data.CreateTime.TimeOfDay;
                            GetBomLookList(bomdetaillist.children[i].data.Id, bomdetaillist.children[i], users, BTid, bomDesignDetail);
                        }
                    }
             
                }
            }
            //&&t.CreatorUserId == _abpSession.GetUserId()
            return bomdetaillist;
        }

        /// <summary>
        /// Bom子级表格树查看
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public BomDetaillist GetBomChildTreeGrid(GetBomNodeTreeListInput input)
        {
            var userData = _userRepository.GetAll().ToList();
            // var queryBomdesign = _bomDesignDetailrepository.FirstOrDefault(t => t.Id == input.BomId);
            //if (queryBomdesign.CreatorUserId != _abpSession.GetUserId())
            // {
            //     throw new UserFriendlyException("非本人创建，不能查看！");
            // }
            var bomDetailList = _bomDesignDetailrepository.GetAll().ToList();
            List<BomDetaillist> querybomdetaillists = null;
            querybomdetaillists = (from bomdetaillistTwo in bomDetailList.Where(t => t.Id == input.BomId).WhereIf(input.Bs == 3, t => t.Status == DocumentStatus.已发布 || t.Status == DocumentStatus.编制中 || t.Status == DocumentStatus.被驳回 || t.Status == DocumentStatus.审核中)//针对于bom变更修改用量和维护查看
                                   .WhereIf(input.Bs == 2, t => t.Status == DocumentStatus.审核中 || t.Status == DocumentStatus.已发布 || t.Status == DocumentStatus.被驳回)//针对于我的审批未审批 和已审批的查看
                                   join materialasContent in _materialsContentrepository.GetAll() on bomdetaillistTwo.MaterialId equals materialasContent.Id
                                   join matialsNode in _materialsNoderepository.GetAll() on materialasContent.MaterialsNodeId equals matialsNode.Id
                                   join user in userData on bomdetaillistTwo.CreatorUserId equals user.Id into Joinmu
                                   from mu in Joinmu.DefaultIfEmpty()
                                   select new BomDetaillist
                                   {
                                       data = new BomEditChildData
                                       {
                                           BomDesignId = bomdetaillistTwo.BomDesignId,
                                           MaterialId = bomdetaillistTwo.MaterialId,
                                           ParentMaterialId = bomdetaillistTwo.ParentMaterialId,
                                           Unit1BomDosage = 1,
                                           MaterialNo = materialasContent.MaterialNo,
                                           MaterialName = materialasContent.MaterialName,
                                           LevelRelationship = bomdetaillistTwo.LevelRelationship,
                                           Id = bomdetaillistTwo.Id,
                                           LevelNum = bomdetaillistTwo.LevelNum,
                                           MaterialTypeName = matialsNode.MaterialTypeName,
                                           Model = materialasContent.Model,
                                           Remark = materialasContent.Remark,
                                           MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialasContent.MaterialProperty.ToString()).ToString(),
                                           Status = (int)bomdetaillistTwo.Status == (int)DocumentStatus.已发布 ? (int)bomdetaillistTwo.Status : (int)bomdetaillistTwo.Status == (int)DocumentStatus.被驳回 ? (int)bomdetaillistTwo.Status : (int)bomdetaillistTwo.Status == (int)DocumentStatus.审核中 ? (int)bomdetaillistTwo.Status : -1,
                                           Attribute = materialasContent.MaterialProperty,
                                           Btid = input.BomId,
                                           CreateUserName = mu.Surname + mu.Name,

                                       },
                                       children = new List<BomDetaillist>()
                                   }).ToList();
            if (querybomdetaillists != null && querybomdetaillists.Count() > 0)
            {
                BomDetaillist bomDetaillist = GetBomLookList(querybomdetaillists[0].data.Id, querybomdetaillists[0], userData, input.BomId,bomDetailList);
                return bomDetaillist;
            }
            return null;
        }
        /// <summary>
        /// 导出BOM内容
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> GetBomContentToExcel(Guid bomDesignId)
        {
            //查出该bom下的相关数据
            var queryBomData = (from bomDesignData in _bomDesignrepository.GetAll().Where(t => t.Id == bomDesignId)
                                join bomdDesingDetailData in _bomDesignDetailrepository.GetAll() on bomDesignData.Id equals bomdDesingDetailData.BomDesignId
                                join materialslContentData in _materialsContentrepository.GetAll() on bomdDesingDetailData.MaterialId equals materialslContentData.Id
                                join materialsNode in _materialsNoderepository.GetAll() on materialslContentData.MaterialsNodeId equals materialsNode.Id
                                 into materialsNodeData
                                from mn in materialsNodeData.DefaultIfEmpty()
                                join code in _sysCodeRepository.GetAll() on materialslContentData.UnitId equals code.Id
                                into codeData
                                from cd in codeData.DefaultIfEmpty()
                                select new BomDetaillist
                                {
                                    data = new BomEditChildData
                                    {
                                        MaterialName = materialslContentData.MaterialName,
                                        MaterialNo = materialslContentData.MaterialNo,
                                        Unit1BomDosage = bomdDesingDetailData.Unit1BomDosage,
                                        Model = materialslContentData.Model,
                                        LevelNum = bomdDesingDetailData.LevelNum,
                                        //Attribute = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialslContentData.MaterialProperty.ToString()),
                                        Attribute = materialslContentData.MaterialProperty,
                                        MaterialTypeName = mn.MaterialTypeName,
                                        UnitName = cd.Code,
                                        ParentId = bomdDesingDetailData.ParentId,
                                        MaterialId = bomdDesingDetailData.MaterialId,
                                        Id = bomdDesingDetailData.Id,
                                        MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialslContentData.MaterialProperty.ToString()).ToString()
                                    }
                                }
                               ).
                               Union(
                                from bomDesignTow in _bomDesignrepository.GetAll().Where(t => t.Id == bomDesignId)
                                join materialslContentData in _materialsContentrepository.GetAll() on bomDesignTow.MaterialsContentId equals materialslContentData.Id
                                select new BomDetaillist
                                {
                                    data = new BomEditChildData
                                    {
                                        MaterialName = materialslContentData.MaterialName,
                                        LevelNum = 1,
                                        Id = bomDesignTow.Id,
                                        MaterialPropertyName = Enum.Parse(typeof(MaterialsEnum.MaterialProperty), materialslContentData.MaterialProperty.ToString()).ToString()
                                    }
                                }
                                );


            if (queryBomData != null)
            {
                BomDetaillist bomDetaillist = new BomDetaillist();
                queryBomData = queryBomData.OrderBy(t => t.data.LevelNum);
                OrderBomDetaillist(queryBomData.ToList(), Guid.Empty);
                return _bomExportToExcel.ExportToFile(bomDetaillists);
            }
            return null;
        }
        /// <summary>
        /// 对结果集进行重组
        /// </summary>
        /// <param name="queryBomData"></param>
        /// <returns></returns>
        private List<BomDetaillist> OrderBomDetaillist(List<BomDetaillist> queryBomData, Guid guid)
        {
            var queryBom = queryBomData.Where(t => t.data.ParentId == guid);
            if (queryBomData.Count > 0)
            {
                if (queryBom.Count() > 0)
                {
                    foreach (BomDetaillist bomDetaillist in queryBom)
                    {
                        bomDetaillists.Add(bomDetaillist.data);
                        OrderBomDetaillist(queryBomData, bomDetaillist.data.Id);
                    }
                }
            }
            return null;
        }

        private ResultMessage CheckMessage(BomImprotDto ljenlist,MaterialsContent materialsContents) 
        {
            ResultMessage rm = new ResultMessage();
            var queryNode = _materialsNoderepository.GetAll().WhereIf(!ljenlist.MaterialTypeName.IsNullOrWhiteSpace(), t => t.MaterialTypeName == ljenlist.MaterialTypeName).FirstOrDefaultAsync().Result;
            var queryNodeTwo = _materialsNoderepository.GetAll().WhereIf(!ljenlist.MaterialSegmentationName.IsNullOrWhiteSpace(), t => t.MaterialTypeName == ljenlist.MaterialSegmentationName).FirstOrDefaultAsync().Result;
            if (materialsContents != null)
            {
                var queryNodeOld = _materialsNoderepository.GetAll().Where(t => t.Id == materialsContents.MaterialsNodeId).FirstOrDefaultAsync().Result;
                var queryNodeTwoOld = _materialsNoderepository.GetAll().Where(t => t.Id == materialsContents.MaterialCategoryId).FirstOrDefaultAsync().Result;
                //如果物料存在 校验物料类别是不是对应的 还有可能物料类别没有 需要提示创建
                if (materialsContents.MaterialsNodeId != queryNode.Id || materialsContents.MaterialCategoryId != queryNodeTwo.Id)
                {
                    rm.code = 1;
                    rm.Message = "该物料：" + ljenlist.MaterialName + "，与原有物料建模不对应，请确认！原类别为：" + queryNodeOld.MaterialTypeName + ",原细分类别为：" + queryNodeTwoOld.MaterialTypeName;
                    return rm;
                }
                //物料不存在 那就校验类别是不是存在
                if (queryNode == null && queryNodeTwo == null)
                {
                    rm.code = 1;
                    rm.Message = "该物料：" + ljenlist.MaterialName + "，没有创建物料类别，请创建!" + "物料类别：" + ljenlist.MaterialTypeName + "细分类别：" + ljenlist.MaterialSegmentationName;
                    return rm;
                }
                else if (queryNode == null)
                {
                    rm.code = 1;
                    rm.Message = "该物料：" + ljenlist.MaterialName + "，没有创建物料类别，请创建!" + "物料类别：" + ljenlist.MaterialTypeName;
                    return rm;
                }
            }
            return rm;
        }

        /// <summary>
        /// 导入设计bom
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMessage> GetExcelToBomDesignContent(IFormFile file, Guid guid)
        {
            ResultMessage result = new ResultMessage();
            if (file == null)
            {
                result.code = 1;
                result.Message = "没有找到有效文件";
                return result;
                //throw new UserFriendlyException("没有找到有效文件");
            }
            try
            {
                StringBuilder errorMsg = new StringBuilder();
                // 单元格抬头
                // key：实体对象属性名称，可通过反射获取值
                // value：属性对应的中文注解
                Dictionary<string, string> cellheader = new Dictionary<string, string> {
                        { "MaterialNoParent", "父级物料图号" },
                        { "MaterialModuleParent", "父级物料型号" },
                        { "MaterialNo", "产品图号" },
                        { "MaterialName", "产品名称" },
                        { "Model", "规格" },
                        { "MaterialProperty", "物料属性" },
                        { "MaterialTypeName", "物料类别" },
                        { "MaterialSegmentationName", "细分类别" },
                        { "Unit", "单位" },
                        { "Unit1BomDosage", "单位用量" },
                        { "Remark", "备注" }
            };
                // 1.2解析文件，存放到一个List集合里
                List<BomImprotDto> enlist = _bomImportToTable.GetExcelList<BomImprotDto>(cellheader, file, out errorMsg);

                enlist = enlist.Where(t => t.MaterialNo != null).ToList();
                if (guid == Guid.Empty)
                {
                    result.code = 1;
                    result.Message = "部套ID不能为空";
                    return result;
                }
                else
                {

                    var queryBomDesignDataParent = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == guid).Result;
                    if (queryBomDesignDataParent != null)
                    {
                        var queryMaterialsData = _materialsContentrepository.FirstOrDefaultAsync(t => t.Id == queryBomDesignDataParent.MaterialId).Result;
                        if (queryMaterialsData.MaterialNo != enlist[0].MaterialNoParent) 
                        {
                            result.code = 1;
                            result.Message = "部套级图号不同，不能导入！（图号不同或有空格）";
                            return result;
                        }
                        // var queryBomParent = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == queryBomDesignDataParent.ParentId).Result;
                        //if (queryBomParent != null)
                        //{
                        //如果需要修改二级节点  不同用户不能修改
                        //var userData = _userRepository.GetAll().ToList()[0];
                        if (queryBomDesignDataParent.CreatorUserId != GetCurrentUser().Id) //add 11/30
                        {
                            result.code = 1;
                            result.Message = "非本人创建，不能导入！";
                            return result;
                            //throw new UserFriendlyException("非本人创建，不能导入！");
                            // }
                        }
                        //else
                        //{
                        //    result.code = 1;
                        //    result.Message = "该发次bom节点异常";
                        //    return result;
                        //    //throw new UserFriendlyException("该发次bom节点异常");
                        //}
                    }
                }
                //校验组件图号和零件图号是否相同 如果相同提示
                List<BomImprotDto> zjListVerify = enlist.Where(t => t.MaterialTypeName =="无"||t.MaterialSegmentationName =="无"||t.MaterialProperty=="组件").ToList();

                List<BomImprotDto> ljenlist = enlist.Where(t => t.MaterialProperty == MaterialsEnum.MaterialProperty.零件.ToString()&& t.MaterialTypeName != "无" || t.MaterialSegmentationName != "无"&&t.MaterialProperty != "组件").ToList();
                int verifyCount = 0;
                string allNo = string.Join(",", enlist.Select(t => t.MaterialNo));
                if (zjListVerify.Count > 0 && ljenlist.Count > 0) 
                {
                    BomImprotDto verifyData = (from zjlistData in zjListVerify
                                   join ljenlistData in ljenlist on zjlistData.MaterialNo equals ljenlistData.MaterialNo
                                   select zjlistData).FirstOrDefault();
                    if (verifyData != null) 
                    {
                        result.code = 1;
                        result.Message ="图号："+ verifyData.MaterialNo+"，组件和零件重复，请修改！";
                        return result;
                    }
                }
                #region 校验
                #region 检测是否必填与值的有效性
                for (int i = 0; i < ljenlist.Count; i++)
                {

                    BomImprotDto en = ljenlist[i];
                    string errorMsgStr = "第" + (i + 2) + "行数据检测异常：";
                    bool isHaveNoInputValue = false; // 是否含有未输入项
                    if (string.IsNullOrEmpty(en.MaterialNoParent))
                    {
                        errorMsgStr += "父级物料图号不能为空；";
                        isHaveNoInputValue = true;
                    }
                    else
                    {
                        if (!allNo.Contains(en.MaterialNoParent))
                        {
                            //       var queryBtCount = (_materialsContentrepository.GetAll().Where(t => t.MaterialNo == (en.MaterialNoParent).Trim()&&t.Model=="-"&&(t.MaterialProperty==(int)MaterialsEnum.MaterialProperty.组件))
                            // //.WhereIf(!(enlist[0].MaterialModuleParent).IsNullOrWhiteSpace(), t => t.Model == (enlist[0].MaterialModuleParent).Trim().TrimStart())
                            //).ToList();
                            //       if (queryBtCount ==null) 
                            //     {
                            result.code = 1;
                            result.Message = "物料名称：" + en.MaterialName + "，物料图号：" + en.MaterialNo + ",的父级物料图号"+en.MaterialNoParent+"无效！";
                            return result;
                            //   }


                            //  }
                        }
                    }
                    if (ljenlist[i].MaterialNoParent == ljenlist[i].MaterialNo)
                    {
                        result.code = 1;
                        result.Message = "" + ljenlist[i].MaterialName + "，父级图号和物料图号不能相同";
                        return result;
                    }


                    if (string.IsNullOrEmpty(en.MaterialNo))
                    {
                        errorMsgStr += "物料图号不能为空；";
                        isHaveNoInputValue = true;
                    }
                    
                    if (string.IsNullOrEmpty(en.MaterialName))
                    {
                        errorMsgStr += "物料名称不能为空；";
                        isHaveNoInputValue = true;
                    }
                    if (string.IsNullOrEmpty(en.Model))
                    {
                        if (en.MaterialTypeName == "标准件")
                        {
                            errorMsgStr += "规格型号不能为空；";
                            isHaveNoInputValue = true;
                        }
                    }
                    if (string.IsNullOrEmpty(en.MaterialProperty))
                    {
                        errorMsgStr += "物料属性不能为空；";
                        isHaveNoInputValue = true;
                    }
                    if (string.IsNullOrEmpty(en.MaterialTypeName) || string.IsNullOrEmpty(en.MaterialSegmentationName))
                    {
                        errorMsgStr += "物料类别不能为空；";
                        isHaveNoInputValue = true;
                    }
                    else
                    {
                        string modelSplit = "";
                        string yearsNo = "";
                        if (ljenlist[i].MaterialTypeName != ljenlist[i].MaterialSegmentationName)
                        {
                            var materialsNodeCal = _materialsNoderepository.FirstOrDefaultAsync(t => t.MaterialTypeName == ljenlist[i].MaterialTypeName).Result;
                            var materilasCala = _materialsNoderepository.Count(t => t.MaterialsTypeCode.ToString().StartsWith(materialsNodeCal.MaterialsTypeCode.ToString()) && t.MaterialTypeName == ljenlist[i].MaterialSegmentationName);
                            if (materilasCala == 0)
                            {
                                result.code = 1;
                                result.Message = "物料：" + ljenlist[i].MaterialName + "，" + ljenlist[i].MaterialTypeName + "类别下，没有" + ljenlist[i].MaterialSegmentationName + "类别。";
                                return result;
                            }

                        }
                        if (ljenlist[i].MaterialTypeName == "标准件")
                        {

                            int index = ljenlist[i].MaterialNo.LastIndexOf('-');
                            string[] vs = ljenlist[i].MaterialNo.Split();
                            if (ljenlist[i].MaterialNo.Split('-').Length > 1)
                            {
                                modelSplit = (ljenlist[i].MaterialNo.Split('-'))[0];
                                yearsNo = (ljenlist[i].MaterialNo.Split('-'))[1];
                            }
                            else
                            {
                                result.code = 1;
                                result.Message = "该物料：" + ljenlist[i].MaterialName + "，缺少年代号，请确认";
                                return result;
                            }
                        }
                        else if (ljenlist[i].MaterialTypeName == "无")
                        {
                            //查询出原物料信息
                            var queryMaterialsContentJy = _materialsContentrepository.GetAll().Where(t => t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件).WhereIf(!ljenlist[i].MaterialNo.IsNullOrWhiteSpace(), t => t.MaterialNo == ljenlist[i].MaterialNo).WhereIf(!ljenlist[i].Model.IsNullOrWhiteSpace(), t => t.Model == ljenlist[i].Model.Replace("X", "x").Replace("*", "x").Replace("×", "x").Trim()).WhereIf(ljenlist[i].Model.IsNullOrWhiteSpace(), t => t.Model == "-").FirstOrDefaultAsync().Result;
                            //找出对应类别
                            var queryNodecs = _materialsNoderepository.GetAll().Where(t => t.MaterialTypeName == "组件").FirstOrDefaultAsync().Result;
                            //找出对应细分类别 组件没有细分类被
                            //var queryNodeTwocs = _materialsNoderepository.GetAll().WhereIf(!ljenlist[i].MaterialSegmentationName.IsNullOrWhiteSpace(), t => t.MaterialTypeName == ljenlist[i].MaterialSegmentationName).FirstOrDefaultAsync().Result;
                            if (queryMaterialsContentJy != null)
                            {
                                if (queryNodecs != null)
                                {
                                    var queryNodeOld = _materialsNoderepository.GetAll().Where(t => t.Id == queryMaterialsContentJy.MaterialsNodeId).FirstOrDefaultAsync().Result;
                                    var queryNodeTwoOld = _materialsNoderepository.GetAll().Where(t => t.Id == queryMaterialsContentJy.MaterialCategoryId).FirstOrDefaultAsync().Result;
                                    if (queryMaterialsContentJy.MaterialsNodeId != queryNodecs.Id)
                                    {
                                        result.code = 1;
                                        result.Message = "" + ljenlist[i].MaterialName + "，与原物料类别不符" + "原类别：" + (queryNodeOld == null ? "-" : queryNodeOld.MaterialTypeName) + "，原细分类别：-";
                                        return result;
                                        //}
                                    }
                                }
                            }
                        }
                        else
                        {
                            modelSplit = ljenlist[i].MaterialNo;
                        }
                        if (ljenlist[i].MaterialTypeName == "零件")
                        {
                            var queryMaterialsContent = _materialsContentrepository.GetAll().Where(t => t.Model == (ljenlist[i].Model == null ? "-" : ljenlist[i].Model).Trim()).WhereIf(!ljenlist[i].MaterialNo.IsNullOrWhiteSpace(), t => t.MaterialNo == ljenlist[i].MaterialNo).FirstOrDefaultAsync().Result;
                             result = CheckMessage(ljenlist[i], queryMaterialsContent);
                            if (result.code == 1) 
                            {
                                return result;
                            }
                        }
                        else if (ljenlist[i].MaterialTypeName == "标准件") 
                        {
                            var queryMaterialsContent = _materialsContentrepository.GetAll().Where(t => t.Model == ljenlist[i].Model.Trim()&&t.MaterialNo == modelSplit.Trim()).FirstOrDefaultAsync().Result;
                            result = CheckMessage(ljenlist[i], queryMaterialsContent);
                            if (result.code == 1)
                            {
                                return result;
                            }
                        }
                    }
                    //if (string.IsNullOrEmpty(en.MaterialSegmentationName))
                    //{
                    //    errorMsgStr += "物料细分类别不能为空；";
                    //    isHaveNoInputValue = true;
                    //}
                    if (string.IsNullOrEmpty(en.Unit))
                    {
                        errorMsgStr += "物料单位不能为空；";
                        isHaveNoInputValue = true;
                    }
          
                    if (string.IsNullOrEmpty(en.Unit1BomDosage.ToString()))
                    {
                        errorMsgStr += "bom用量列不能为空；";
                        isHaveNoInputValue = true;
                    }


                    if (isHaveNoInputValue) // 若必填项有值未填
                    {
                        en.IsExcelVaildateOK = false;
                        errorMsg.AppendLine(errorMsgStr);
                    }
                }
                #endregion

                #region 2.2检测Excel中是否有重复对象

                //for (int i = 0; i < enlist.Count; i++)
                //{
                //    BomImprotDto enA = enlist[i];
                //    if (enA.IsExcelVaildateOK == false) // 上面验证不通过，不进行此步验证
                //    {
                //        continue;
                //    }
                //    for (int j = i + 1; j < enlist.Count; j++)
                //    {
                //        BomImprotDto enB = enlist[j];
                //        // 判断必填列是否全部重复
                //        if (enA.MaterialNo.Trim() == enB.MaterialNo.Trim())
                //        {
                //            enA.IsExcelVaildateOK = false;
                //            enB.IsExcelVaildateOK = false;
                //            errorMsg.AppendLine("第" + (i + 1) + "行与第" + (j + 1) + "行的必填列重复了");
                //        }
                //        // 判断必填列是否全部重复
                //        //if (enA.Model == enB.Model)
                //        //{
                //        //    enA.IsExcelVaildateOK = false;
                //        //    enB.IsExcelVaildateOK = false;
                //        //    errorMsg.AppendLine("第" + (i + 1) + "行与第" + (j + 1) + "行的必填列重复了");
                //        //}
                //    }
                //}
                #endregion
                #endregion
                #region 数据持久化
                if (enlist.Count > 0 && errorMsg.Length == 0)
                {


                    var queryBtCount = _materialsContentrepository.GetAll().Where(t => t.MaterialNo == (enlist[0].MaterialNoParent).Trim())
                        //.WhereIf(!(enlist[0].MaterialModuleParent).IsNullOrWhiteSpace(), t => t.Model == (enlist[0].MaterialModuleParent).Trim().TrimStart())
                        .WhereIf((enlist[0].MaterialModuleParent).IsNullOrWhiteSpace(), t => t.Model == "-");
                    if (queryBtCount.Count() == 0)
                    {
                        result.code = 1;
                        result.Message = "没有该部套！";
                        return result;
                    }
                    List<BomImprotDto> bomImprotDtos = enlist.Where(t => t.MaterialProperty == "组件").ToList();

                    var queryBomDesignDataParent = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == guid).Result;

                    Guid parentId = Guid.Empty;
                    Guid bomDesignId = Guid.Empty;
                    Guid materiallsId = Guid.Empty;
                    int unitBomDosage = 0;
                    int levelNum = 0;
                    string remark = "";
                    int queryBomCount = 0;
                    BomDesignDetail bomDesignDetail = null;
                    string levelRelationship = "";
                    int materialProperty = 0;
                    //找出部套下有多少组件 计算层级
                    var bomDesignDetailCount = await _bomDesignDetailrepository.CountAsync(t => t.ParentId == guid);
                    for (int i = 0; i < bomImprotDtos.Count; i++)
                    {
                        int levelNumber = i + 1 + bomDesignDetailCount;
                        //if (queryBomDesignDataParent == null) 
                        //{
                        //    return;
                        //}
                        //找出部套下所有的明细统计数量
                        //var queryBomDesignCount = _bomDesignDetailrepository.Count(t => t.ParentId == guid);
                        ////加1
                        //queryBomCount = queryBomDesignCount + 1;
                        var queryMaterialsData = _materialsContentrepository.GetAll().WhereIf(!bomImprotDtos[i].Model.IsNullOrWhiteSpace(), t => t.Model.Trim() == bomImprotDtos[i].Model.Replace("X", "x").Replace("*", "x").Replace("×", "x").Trim()).WhereIf(!bomImprotDtos[i].MaterialNo.IsNullOrWhiteSpace(), t => t.MaterialNo.Trim() == bomImprotDtos[i].MaterialNo.Trim()).FirstOrDefaultAsync().Result;
                        StoreReturnIdDto storeReturnIdDto = new StoreReturnIdDto();
                        if (queryMaterialsData == null)
                        {
                            // throw new UserFriendlyException(bomImprotDtos[i].MaterialNo.Trim()+"该组件不存在！");
                            storeReturnIdDto = await CreateMaterialsContent(bomImprotDtos[i], queryBomCount, queryBomDesignDataParent.BomDesignId);
                            //_iOperationHistoryAppService.InsertOperationLogNew(bomDesignId, BusinessTypes.设计bom, OperationTypes.设计bom导入反向建模, "【导入建模】：名称：" + materialsEditContentDto.MaterialName + "，图号：" + modelSplit + "规格：" + materialsEditContentDto.Model);
                        }
                        List<BomDesignDetail> queryBomDesignDataParentList = null;
                        //计算如果父级图号是组件那么parentid 为该组件的id
                        var queryMaterialsDataParent = _materialsContentrepository.GetAll().WhereIf(!bomImprotDtos[i].MaterialModuleParent.IsNullOrWhiteSpace(), t => t.Model.Trim() == bomImprotDtos[i].MaterialModuleParent.Replace("X", "x").Replace("*", "x").Replace("×", "x").Trim()).
                            WhereIf(!bomImprotDtos[i].MaterialNoParent.IsNullOrWhiteSpace(), t => t.MaterialNo.Trim() == bomImprotDtos[i].MaterialNoParent.Trim()).FirstOrDefaultAsync().Result;
                        if (queryMaterialsDataParent != null)
                        {
                            queryBomDesignDataParentList = _bomDesignDetailrepository.GetAll().Where(t => t.ParentId == guid && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件 && t.MaterialId == queryMaterialsDataParent.Id).ToList();
                        }
                        else
                        {
                            result.code = 1;
                            result.Message = bomImprotDtos[i].MaterialNoParent.Trim() + "不存在！";
                            return result;
                            //throw new UserFriendlyException(bomImprotDtos[i].MaterialNoParent.Trim() + "不存在！");
                        }

                        //如果物料详细存在 并且 父级也存在 
                        if (queryBomDesignDataParent != null)
                        {
                            if (queryMaterialsData != null)
                            {
                                parentId = queryBomDesignDataParentList.Count() > 0 ? queryBomDesignDataParentList.ToList()[0].Id : guid;
                                bomDesignId = queryBomDesignDataParent.BomDesignId;
                                levelNum = queryBomDesignDataParent.LevelNum + 1;
                                materiallsId = queryMaterialsData.Id;
                                unitBomDosage = bomImprotDtos[i].Unit1BomDosage;
                                remark = bomImprotDtos[i].Remark;
                                levelRelationship = queryBomDesignDataParent.LevelRelationship;
                                materialProperty = queryMaterialsData.MaterialProperty;
                            }
                            else
                            {
                                //针对于没有组件新增后赋值
                                parentId = queryBomDesignDataParentList.Count() > 0 ? queryBomDesignDataParentList.ToList()[0].Id : guid;
                                bomDesignId = queryBomDesignDataParent.BomDesignId;
                                //levelNum = queryBomDesignDataParent.LevelNum + (bomDesignDetailCount + 1);
                                levelNum = queryBomDesignDataParent.LevelNum + 1;
                                materiallsId = storeReturnIdDto.MaterialsContentId.Value;
                                unitBomDosage = bomImprotDtos[i].Unit1BomDosage;
                                remark = bomImprotDtos[i].Remark;
                                levelRelationship = queryBomDesignDataParent.LevelRelationship;
                                materialProperty = (int)MaterialsEnum.MaterialProperty.组件;
                            }
                        }
                        bomDesignDetail = new BomDesignDetail
                        {
                            BomDesignId = bomDesignId,
                            ParentId = parentId,
                            Id = Guid.NewGuid(),
                            LevelNum = levelNum,
                            MaterialId = materiallsId,
                            Unit1BomDosage = unitBomDosage,
                            Remark = remark,
                            LevelRelationship = levelRelationship + "." + levelNumber,
                            Status = DocumentStatus.已维护,
                            MaterialProperty = materialProperty
                        };
                        bomDesignDetails.Add(bomDesignDetail);
                        await JoinBom(enlist, bomImprotDtos[i], bomDesignDetail);
                        int count = bomImprotDtos.Where(t => (t.MaterialNoParent).Trim() == (queryMaterialsDataParent.MaterialNo).Trim() && (t.MaterialModuleParent == null ? "-" : t.MaterialModuleParent).Replace("X", "x").Replace("*", "x").Replace("×", "x").Trim() == (queryMaterialsDataParent.Model.Replace("X", "x").Replace("*", "x").Replace("×", "x")).Trim()).Count();
                        if (count == 1)
                        {
                            break;
                        }
                    }
                    Guid logId = Guid.Empty;
                    if (bomDesignDetails.Count() > 0)
                    {
                        List<BomDesignDetail> bomDesignDetailsData = new List<BomDesignDetail>();
                        for (int i = 0; i < bomDesignDetails.Count; i++)
                        {
                            bomDesignDetails[i].OrderNum = i;
                         //   _bomDesignDetailrepository.Insert(bomDesignDetails[i]);
                            //  _unitOfWorkManager.Current.SaveChanges();
                            //guid = bomDesignDetail.BomDesignId;
                            bomDesignDetailsData.Add(bomDesignDetails[i]);
                            logId = bomDesignDetails[i].BomDesignId;
                        }
                        _bomDesignDetailrepository.GetDbContext().BulkInsert(bomDesignDetailsData);
                        var queryBomMaterials = from bomMaterialsData in _materialsContentrepository.GetAll() join bomData in bomDesignDetails on bomMaterialsData.Id equals bomData.MaterialId select bomMaterialsData;
                        foreach (var queryData in queryBomMaterials)
                        {
                            _iOperationHistoryAppService.InsertOperationLogNew(logId, BusinessTypes.设计bom, OperationTypes.Bom导入, "导入：名称：" + queryData.MaterialName + "，图号：" + queryData.MaterialNo + "规格：" + queryData.Model);
                        }
                    }
                }
                if (errorMsg.Length > 0)
                {
                    result.code = 1;
                    result.Message = errorMsg.ToString();
                    return result;
                }
                else
                {
                    result.code = 0;
                    return result;
                    //return "success";
                }
                #endregion
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.Message = ex.Message;
                return result;
            }
        }
        private async Task JoinBom(List<BomImprotDto> bomImprotDtos, BomImprotDto bomImprotParent, BomDesignDetail bomDesignDetail)
        {
            BomDesignDetail bomDesignDetailChild = null;
            List<BomImprotDto> bomImprots = bomImprotDtos;

            //找出子级
            if (bomImprotParent != null)
            {

                bomImprots = bomImprotDtos.Where(t => t.MaterialNoParent.Trim() == bomImprotParent.MaterialNo.Trim()).ToList();
            }
            ////如果没有子级直接添加到list
            if (bomImprots.Count() > 0)
            {
                int index = 0;
                //循环子级 
                for (int i = 0; i < bomImprots.Count; i++)
                {
                    index = i + 1;
                    string modelSplit = "";
                    string yearsNo = "";
                    if (bomImprots[i].MaterialTypeName == "标准件")
                    {
                        modelSplit = (bomImprots[i].MaterialNo.Split('-'))[0];
                        yearsNo = (bomImprots[i].MaterialNo.Split('-'))[1];
                    }
                    else
                    {
                        modelSplit = bomImprots[i].MaterialNo;
                    }
                    //根据id找出原有的materiallsId   
                    var queryMaterialsContent = _materialsContentrepository.GetAll().WhereIf(!(bomImprots[i].Model == null ? "-" : bomImprots[i].Model).Trim().IsNullOrWhiteSpace(), t => t.Model == (bomImprots[i].Model == null ? "-" : bomImprots[i].Model.Replace("X", "x").Replace("*", "x").Replace("×", "x").Trim())).WhereIf(!modelSplit.IsNullOrWhiteSpace(), t => t.MaterialNo == modelSplit).FirstOrDefaultAsync().Result;
                    if (queryMaterialsContent != null)
                    {
                        //验证原有物料是不是导入时的类别 如果不是 提示
                        //var queryNodeMaterials =from materialsContent in queryMaterialsContent
                        //                        join materialsNode in _materialsNoderepository.GetAll().WhereIf(!bomImprots[i].MaterialTypeName.IsNullOrWhiteSpace(),t =>t.MaterialTypeName == bomImprots[i].MaterialTypeName)
                        //                        on materialsContent
                        //                        join materialsNodeTwo in _materialsNoderepository.GetAll().WhereIf(!bomImprots[i].MaterialSegmentationName.IsNullOrWhiteSpace(), t => t.MaterialTypeName == bomImprots[i].MaterialSegmentationName)
                        //                        on materialsContent.


                        bomDesignDetailChild = new BomDesignDetail
                        {
                            ParentId = bomDesignDetail.Id,
                            BomDesignId = bomDesignDetail.BomDesignId,
                            MaterialId = queryMaterialsContent.Id,
                            ParentMaterialId = queryMaterialsContent.Id,
                            Unit1BomDosage = bomImprots[i].Unit1BomDosage,
                            LevelNum = bomDesignDetail.LevelNum + 1,
                            Id = Guid.NewGuid(),
                            Remark = bomImprots[i].Remark,
                            LevelRelationship = bomDesignDetail.LevelRelationship + "." + index,
                            Status = DocumentStatus.已维护,
                            YearsNo = yearsNo,
                            MaterialProperty = queryMaterialsContent.MaterialProperty,
                            WithinComponent = bomImprots[i].MaterialSegmentationName.Trim() == "无" && bomImprots[i].MaterialTypeName.Trim() == "无" ? -2 : 0

                        };
                        bomDesignDetails.Add(bomDesignDetailChild);
                        await JoinBom(bomImprotDtos, bomImprots[i], bomDesignDetailChild);
                    }
                    else
                    {
                        //反向建模
                        StoreReturnIdDto storeReturnIdDto = new StoreReturnIdDto();
                        storeReturnIdDto = await CreateMaterialsContent(bomImprots[i], index, bomDesignDetail.BomDesignId);

                        var queryMaterialsList = _materialsContentrepository.FirstOrDefaultAsync(t => t.Id == storeReturnIdDto.MaterialsContentId).Result;

                        if (queryMaterialsList != null)
                        {
                            bomDesignDetailChild = new BomDesignDetail
                            {
                                ParentId = bomDesignDetail.Id,
                                BomDesignId = bomDesignDetail.BomDesignId,
                                MaterialId = queryMaterialsList.Id,
                                ParentMaterialId = queryMaterialsList.Id,
                                Unit1BomDosage = bomImprots[i].Unit1BomDosage,
                                LevelNum = bomDesignDetail.LevelNum + 1,
                                Id = Guid.NewGuid(),
                                Remark = bomImprots[i].Remark,
                                LevelRelationship = bomDesignDetail.LevelRelationship + "." + index,
                                Status = DocumentStatus.已维护,
                                YearsNo = yearsNo,
                                MaterialProperty = queryMaterialsList.MaterialProperty,
                                WithinComponent = bomImprots[i].MaterialSegmentationName.Trim() == "无" && bomImprots[i].MaterialTypeName.Trim() == "无" ? -2 : 0
                            };
                            bomDesignDetails.Add(bomDesignDetailChild);
                            await JoinBom(bomImprotDtos, bomImprots[i], bomDesignDetailChild);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 发送审批
        /// </summary>
        private void SendApproval(BomApprovalDto bomApprovalDto)
        {
            //var bomConent = _bomDesignrepository.GetAllIncluding(t => t.BomDesignDetails).Where(d => d.Id == bomApprovalDto.BomId).FirstOrDefault();
            //var bomDesignConent = _bomDesignDetailrepository.GetAll().Where(d => d.Id == bomApprovalDto.BomId).FirstOrDefault();
            //var bomAllData = ObjectMapper.Map<BomDesignDetailDto>(bomDesignConent);
            //BusinessApplicationDto businessApplicationDto = new BusinessApplicationDto
            //{
            //    //AppContent = bomApprovalDto.Remark,
            //    //bomDesign = bomAllData,
            //    //BAppType = bomApprovalDto.WfNameId,
            //    //FunModule = "工艺管理",
            //    //Menu = "设计BOM",
            //    //WorkAuditorList = bomApprovalDto.WorkAuditorList
            //};
            // _workFlowAppService.PushBusinessApplication(ObjectMapper.Map<BusinessApplicationDto>(businessApplicationDto));
        }
        /// <summary>
        /// 启用停用
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task UpdateBomDesignEnable(BomDesignEnbleDto input)
        {
            if (input != null)
            {
                var queryBomDesignData = _bomDesignrepository.FirstOrDefaultAsync(t => t.Id == input.Id).Result;
                if (queryBomDesignData != null)
                {
                    queryBomDesignData.IsUsed = input.IsUsed;
                    await _bomDesignrepository.UpdateAsync(queryBomDesignData);
                }
                else
                {
                    throw new UserFriendlyException("无该Bom相关数据");
                }
            }
        }
        public async Task<StoreReturnIdDto> CreateMaterialsContent(BomImprotDto bomImprotDtos, int index, Guid bomDesignId)
        {
            StoreReturnIdDto storeReturnIdDto = new StoreReturnIdDto();
            Guid guid = Guid.Empty;
            var materNode = _materialsNoderepository.FirstOrDefaultAsync(t => t.MaterialTypeName == bomImprotDtos.MaterialTypeName).Result;
            var materCategoryNode = _materialsNoderepository.FirstOrDefaultAsync(t => t.MaterialTypeName == bomImprotDtos.MaterialSegmentationName).Result;
            if (materNode == null || materCategoryNode == null)
            {
                var queryMaterilasNodes = _materialsNoderepository.FirstOrDefaultAsync(t => t.MaterialTypeName == "组件").Result;
                if (queryMaterilasNodes != null)
                {
                    guid = queryMaterilasNodes.Id;
                }
                else
                {
                    storeReturnIdDto.Message = "请先创建类别：" + bomImprotDtos.MaterialName;
                    storeReturnIdDto.code = 1;
                    return storeReturnIdDto;
                }
            }
            var unitCode = _sysCodeRepository.FirstOrDefaultAsync(t => t.Description == bomImprotDtos.Unit).Result;
            string modelSplit = "";
            if (bomImprotDtos.MaterialTypeName == "标准件")
            {
                modelSplit = (bomImprotDtos.MaterialNo.Split('-'))[0];
            }
            else
            {
                modelSplit = bomImprotDtos.MaterialNo;
            }
            MaterialsEditContentDto materialsEditContentDto = new MaterialsEditContentDto
            {
                MaterialNo = modelSplit.Trim(),
                MaterialName = bomImprotDtos.MaterialName.Trim(),
                Model = bomImprotDtos.Model == null ? "" : bomImprotDtos.Model.Trim(),
                MaterialsNodeId = materNode == null ? guid : materNode.Id,
                UnitId = unitCode == null ? Guid.Empty : unitCode.Id,
                IsUsed = (int)MaterialsEnum.UsedIs.True,
                IsKeyPart = (int)MaterialsEnum.IsKeyPart.True,
                IsStandard = (int)MaterialsEnum.IsStandard.True,
                Remark = bomImprotDtos.Remark,
                MaterialTypeCode = materNode == null ? guid + "_" + index : materCategoryNode == null ? guid.ToString() : materCategoryNode.MaterialsTypeCode.ToString() + "_0" + index,
                MaterialProperty = bomImprotDtos.MaterialTypeName == "无" || bomImprotDtos.MaterialSegmentationName == "无" || bomImprotDtos.MaterialTypeName ==null? (int)MaterialsEnum.MaterialProperty.组件 : (int)MaterialsEnum.MaterialProperty.零件,
                MaterialCategoryId = materCategoryNode == null ? Guid.Empty : materCategoryNode.Id,

                Batch = "001"
            };
            StoreReturnIdDto returnIdData = await _materialsAppService.CreateOrUpdateMaterialsContent(materialsEditContentDto);
            _unitOfWorkManager.Current.SaveChanges();
            //_iOperationHistoryAppService.InsertOperationLogNew(bomDesignId, BusinessTypes.设计bom, OperationTypes.设计bom导入反向建模, "【导入建模】：名称：" + materialsEditContentDto.MaterialName + "，图号：" + modelSplit + "规格：" + materialsEditContentDto.Model);
            return returnIdData;
        }

        /// <summary>
        /// 更新bom用量的状态公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task UpdateStatus(BomDesignDetailDto input)
        {
            try
            {
                var btList = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == input.Btid && t.BomDesignId == input.BomDesignId).Result;
                var childList = _bomDesignDetailrepository.GetAll().Where(t => t.LevelRelationship.StartsWith(btList.LevelRelationship) && t.BomDesignId == input.BomDesignId);
                List<BomDesignDetail> bomDesignDetails = new List<BomDesignDetail>();
                foreach (BomDesignDetail bomDesignDetail in childList)
                {
                    if (bomDesignDetail.Status == DocumentStatus.编制中)
                    {
                        continue;
                    }
                    else if (bomDesignDetail.Status == DocumentStatus.已发布 || bomDesignDetail.Status == DocumentStatus.被驳回)
                    {
                        bomDesignDetail.Status = DocumentStatus.编制中;
                        bomDesignDetails.Add(bomDesignDetail);
                    }
                }
                await _bomDesignDetailrepository.GetDbContext().BulkUpdateAsync(bomDesignDetails);
                //更新bomchange主表数据
                //var bomchange = _bomChangeContentRepository.FirstOrDefaultAsync(t => t.BTId == input.Btid && t.BomDesignId == input.BomDesignId).Result;
                //if (bomchange != null)
                //{
                //    bomchange.Status = DocumentStatus.编制中;
                //    await _bomChangeContentRepository.UpdateAsync(bomchange);
                //}
            }
            catch
            {
                throw new UserFriendlyException("更新审核状态出错");
            }
        }

        /// <summary>
        /// 发送审核更新状态公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SendAuditUpdateStatus(BomDesignDetail input)
        {
            try
            {
                if (input != null)
                {
                    List<BomDesignDetail> bomDesignDetails = new List<BomDesignDetail>();
                    var childList = _bomDesignDetailrepository.GetAll().Where(t => t.LevelRelationship.StartsWith(input.LevelRelationship) && t.BomDesignId == input.BomDesignId);
                    foreach (BomDesignDetail bomDesignDetail in childList)
                    {

                        if (bomDesignDetail.Status == DocumentStatus.审核中)
                        {
                            continue;
                        }
                        else if (bomDesignDetail.Status == DocumentStatus.已维护 || bomDesignDetail.Status == DocumentStatus.编制中 || bomDesignDetail.Status == DocumentStatus.被驳回 || bomDesignDetail.Status == DocumentStatus.已发布)
                        {
                            bomDesignDetail.ModifiChangeId = input.ModifiChangeId;
                            bomDesignDetail.Status = DocumentStatus.审核中;
                            bomDesignDetails.Add(bomDesignDetail);
                        }
                    }
                    await _bomDesignDetailrepository.GetDbContext().BulkUpdateAsync(bomDesignDetails);
                }
            }
            catch
            {
                throw new UserFriendlyException("发送审核，更新状态出错");
            }
        }
        ///<summary>
        /// 截前后字符串
        ///</summary>
        ///<param name="val">原字符串</param>
        ///<param name="str">要截掉的字符串</param>
        ///<param name="bAllStr">是否对整个字符串进行截取
        ///如果为true则对整个字符串中匹配的进行截取
        ///如果为false则只截取前缀或者后缀</param>
        ///<returns></returns>
        public string ToTrimStartAndEnd(string val, string str, bool bAllStr = false)
        {
            return Regex.Replace(val,
                @"(^(" + str + ")" + (bAllStr ? "*" : "") + "|(" + str + ")" + (bAllStr ? "*" : "") + "$)", "");
        }
    }


}
